2

I have a form to which I am appending form elements on the click event. I want to append options to a drop down(select options) which is created dynamically as the user types the input.

The user input is saved in a variable as he types using the keyup event in the following manner:

$("#options_"+id).keyup(function(){

        var val_options = $('#options_'+id).val(); //user input is stored in the variable val_options

        var options = val_options.split(','); //input is exploded with a comma       

        var len = options.length;

            for(var i =0;i<len;i++)
            {                   

                var drop_options = "<option id='option_'"+i+">"+options[i]+"</option>";
                $("#select_"+id).append(drop_options);                  
            }

    });

Now the tags created dynamically are appended to the tag having that particular id.

The problem I am facing here is that when the user types a single character, it gets appended as an option in the drop down menu. I only want it to append when the user presses the comma (,) key.

4

2 回答 2

2

Try something like this:

$("#options_"+id).keyup(function(event){
    if (event.which !== 188) { // 188 is the keycode for ','
        return; // Do nothing.
    }

    var $this = $(this),
        val_options = $this.val(),
        options = val_options.split(','),
        $dropdown = $("#select_"+id);

    $dropdown.empty();

    for(var i =0;i<options.length-1;i++) {
        $dropdown.append(
            "<option id='option_'"+i+">"+options[i]+"</option>"
        );                  
    }
});
于 2012-06-29T12:24:07.810 回答
2
$("#options_" + id).keyup(function(e) {

    var val_options = $(this).val(); // getting input values
        options = val_options.split(','); // getting all values as array

    // checking for comma
    if (val_optons.indexOf(',') >= 0 ) {

        // if comma found then start append
        var options = val_options.split(',');
        var drop_options = ''; // take an empty string

        // looping over all values with
        // input fields separated by comma

        for (var i = 0; i < options.length; i++) {

            // making string of all options
            drop_options += "<option id='option_'" + i + ">" + options[i] + "</option>";
        }

        // append all option to select
        // here .html() will remove all previous
        // options and append newly 

        $("#select_" + id).html(drop_options);

    }
});

DEMO

Calling .append() within loop cause slower performance, so try to avoid that.

于 2012-06-29T12:24:31.917 回答