开发者

How to generate dynamic form using JavaScript/JQuery?

Suppose a form.php file, and there is "add" button, once it's clicked, a drop down list will show, to let you choose which type of input type you want. For example:

<select name="Type">
        <option value="Text">Text</option>
    <option value="MultipleChoice">MultipleChoice</option>
    <option value="Checkbox">Checkbox</option>
</select>

My question is, I don't know how to implement the function that, once the type is chosen, suppose checkbox, then a checkbox will shown, and could let you input the label of each checkbox, you can do this开发者_运维知识库 one by one. Also I want to make this process could happen iteratively. I'm not sure if I explain clearly, it's a little bit like the google form function. Any ideas? If providing some codes would be better. Thanks!


Here is plain vanilla old school HTML/JS

<select name="Type" onchange="showformelement(this.value)">
    <option value="text">Text</option>
<option value="MultipleChoice">MultipleChoice</option>
<option value="Checkbox">Checkbox</option>
</select>
<script>
function showformelement(whichelement){
    //use whichelement to embedd element in DOM
}
</script>

If you can use jQuery or similar toolkit it may be a much simpler job


I know what are you looking for, just let you know that it isn't a simple script, it will have way too many functions and will be little hard to build.

Just to start, if you search on the web for PHP and jQuery based form builders and similar other things, you will find many ready to use scripts. Well, if you don't want to search for one, the principle logic will look like following:

PS: I will explain how to develop using jQuery.

<select id="options">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>

<script>
$(document).ready(function(){
$('#options').change(function(){
var optSelected = $('#options option:selected').val()    
  if(optSelected == 1){
    // Shows up and div with Checkboex for edit
  }
  if(optSelected == 2){
    // Shows up and div with Combobox for edit
  }
  if(optSelected == 3){
    // Shows up and div with Textbox for edit
  }
  })
})
</script>

After doing that, you will need to build the options of each type... There is too much work... look, I didn't write here your script, I just explained you how to build...

This is a huge system...you will need to know a bit of JavaScript to make one of these...


Even simpler, without needing to do any casing or conditioning, (uses jQuery).

Example: http://jsfiddle.net/SMAfA/

$(function() {
    $("#type").change(function() {
        type = $("option:selected", this).text();
        $("#target").append("<input type="+type+">");
    })
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜