开发者

How to generate input box by jQuery

Suppose I have a drop down box to define how many row of input box, then generate the designated rows of input box, after that each row of input box with attach a drop down box, it can define how many input box of each row, illustrated as below:

开发者_开发技巧

How to generate input box by jQuery

Could anyone suggest the snippet for this procedure?

Thanks


I will not give you specific snippet for this, but will give you some tips instead. Here they are:

  1. Think about HTML structure for this (eg. separate first select from the rest of the form, eg. give the rest of the form a <div> with form-dynamic-fields class so it will serve as a container for dynamically generated fields),
  2. Use jQuery's .delegate() function to attach events (delegate them to the select boxes within dynamic fields),
  3. Depending on the selection of specific select field, add, remove or replace appropriate rows (when changing main select's field value) or fields (when changing value of select for specific row),
  4. You should probably use onchange event.

Example usage of .delegate() function can be like that:

jQuery('.form-dynamic-fields').delegate('select', 'change', function(event){
    var fields_in_a_row = jQuery(this).val(); // how many fields in current row
    // insert or remove appropriate number of fields for current row here
});

and it will work for every <select> fields generated dynamically as far as the container with class form-dynamic-fields remains their parent element and is not deleted.

So, given you the clue about how you can structure your form, how to attach events, what should they do and what event should you use, I would like to...

...encourage you to test different solutions and share information about the progress you have made with solving this issue.

EDIT:

Some working example to encourage you more (see jsFiddle):

  • HTML:

    <form class="form-dynamic" action="" method="post">
        <select name="number_of_rows">
            <option>0</option>
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
        </select>
        <div class="form-dynamic-fields">
    
        </div>
    </form>
    
  • JavaScript (executed onDomReady):

    jQuery('.form-dynamic').delegate('select[name="number_of_rows"]', 'change', function(event){
        var field_template = '<input type="text" name="row[]" /><br />';
        var howmany = parseInt(jQuery(this).val());
        var container = jQuery(this).parent('.form-dynamic').find('.form-dynamic-fields').empty();
        if (howmany > 0){
            for (i=1; i<=howmany; i++){
                container.append(jQuery('<div class="form-dynamic-row"><input type="text" name="rows[' + i +'][]" /> <select name="rows_counts[]" data-row-id="' + i + '"><option>1</option><option>2</option><option>3</option><option>4</option></select></div>'));
            }
        }
    });
    
    jQuery('.form-dynamic').delegate('select[name="rows_counts[]"]', 'change', function(event){
        var parent = jQuery(this).parent('.form-dynamic-row');
        parent.find('input[type="text"]').remove();
        var howmany = jQuery(this).val();
        var row_id = jQuery(this).attr('row-id');
        for (i=1; i<=howmany; i++){
            parent.prepend('<input type="text" name="rows[' + row_id + '][' + i + ']" />');
        }
    });
    

What you need to do is:

  • clean the code,
  • add some styling (so the fields have proper width),
  • check and eventually fix name attributes of <input> fields,
  • fix problems you may encounter when implementing it,

I hope it helped :)


Not letting you do your homework is not a good thing for the SO community, but i could not resist this one. My apologies guys.

Online demo: http://jsfiddle.net/E46P5/

var input  = '<input type="text" />'; //input html
var select = '<select>'+ //select html
                    '<option value="0"></option>'+
                    '<option value="1">1</option>'+
                    '<option value="2">2</option>'+
                    '<option value="3">3</option>'+
                    '<option value="4">4</option>'+
                    '<option value="5">5</option>'+
              '</select>';

var row = '<p>'+ input + select + '</p>'; //row html
var container = $("#container"); //cache selector for better performance
var i = 0; // variable used in loop

$("#rowNumber").change(function(){ //when the main select changes
    var numRows = $(this).val(); //get its value

    container.html(""); //empty the container

    for(i=1; i<= numRows; i++){ 
        container.append(row); //and append a row from 1 to the numRows
    }
    });
    container.delegate('p > select','change',function(){ //when a select inside
        //a row changes
        var numInputs = $(this).val(); //get its value
        var parent = $(this).parent(); //select its parent
        var width = 170/numInputs;
        parent.html(""); //empty it
        for(i=1; i<=numInputs; i++){
            parent.append(input); //append an input from 1 to the numINputs
        }
        parent.append(select); //and append a select
    });

Althought i could not get the width of the inputs to depend on how many they are inside a row.


Here's a very simple and effective way to do this with JQuery. You can use this code easily to add/decrease the amount of options in dropdown menus and you can easily edit the id/class names to something else and style them as well. It's very flexible way to do this! It names the inputs based on how many you have (class="input-1" or class="input-2") so you can use those names to style the width in your css.

HTML:

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

<div id="myForm">
</div>

JQuery:

$(document).ready(function() {
    $('#dropdown').change(function() {
        $('#myForm').empty();
        for (var i=0; i<$('#dropdown').val(); i++) {
            $('#myForm').append('<div class="inputGroup"><input type="input" class="input" /><select class="select"><option></option><option value="1">1</option><option value="2">2</option></select></div>');          
        }
        $('select').bind('change', changeInputs);
    });
});

function changeInputs() {
    var string;
    string = "";
    for (var i=0; i<$(this).val(); i++) {
        string = string + '<input type="input" class="input-'+$(this).val()+'" />';
    }     
    $(this).parents('.inputGroup').html(string + '<select class="select"><option></option><option value="1">1</option><option value="2">2</option></select>');
    $('select').bind('change', changeInputs);
}

Feel free to test it out: http://jsfiddle.net/Ag6GD/2/

Hopefully it helped you out.


Here is a working solution.

Here is the HTML:

<select onchange="javascript:local.drop1Change(this);" >
    <option value="-">select item</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
<div id="workArea"></div>

then some javascript:

<script src="/Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script type="text/javascript">
    var local = {};
    local.changeInner = function (containerId, ctrl) {
    var target = $("#" + containerId);
    target.empty();
    var len = $(ctrl).val();
    for (q = 0; q < len; q = q + 1) {
        var el = document.createElement("input");
        target.append(el);
    }
    target.append(ctrl);
};  
local.drop1Change = function (ctrl) {
    var selectedValue = $(ctrl).val();
    var len = selectedValue;
    var area = $("#workArea");
    area.empty();
    for (x = 0; x < len; x=x+1) {
        var container = document.createElement("div");
        var el = document.createElement("input");
        container.id = "container" + x;
        var s1 = document.createElement("span");
        $(s1).html('<select style="margin:2px 2px 2px 2px;"      
         onchange="javascript:local.changeInner(\'' + container.id + '\', this);">   <option value="1" selected>1</option><option value="2">2</option><option value="3">3</option></select>');
        $(container).append(el);
        $(container).append(s1);
        area.append(container);
    }
};
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜