Dynamically add option to chosen select multiple JQuery plugin

柔情痞子 提交于 2019-12-04 05:03:31

You should try out the select2 plugin which is based off of chosen plugin but it works well with adding elements dynamically.

Heres the link: http://ivaynberg.github.com/select2/

Look at the example for auto-tokenization I think that might be what you are looking for.

I needed this today so I wrote something like this:

$(function() {
    // form id
    $('#newtag').alajax({
        // data contains json_encoded array, sent from server
        success: function(data) {
            // this is missing in alajax plugin
            data = jQuery.parseJSON(data);
            // create new option for original select
            var opt = document.createElement("OPTION");
            opt.value = data.id;
            opt.text = data.name;
            opt.selected = true;
            // check if the same value already exists
            var el = $('#tags option[value="' + opt.value + '"]');
            if( !el.size() ) {
                // no? append it and update chosen-select field
                $('#tags').append( opt ).trigger("chosen:updated");
            } else {
                // it does? check if it's already selected
                if(!el[0].selected) {
                    // adding already existent element in selection
                    el[0].selected = true;
                    $('#tags').trigger("chosen:updated");
                } else {
                    alert("Already selected and added.");
                }
            }


        }
    })
});

"#"newtag is a form, ".alajax" is a plugin that sends form data in async way and returns server's response in JSON format. In the controller I check if a tag exists otherwise I create it. In response I five "jsoned" tag object.

just call it keyup_check keydown_check is called before the pressed letter is initialized unlike keyup_check

I created a jsfiddle of jquery chosen which takes text and create as option. In earlier version of jquery chosen have facility create option.

create_option: true;
persistent_create_option: true;
skip_no_results: true;

You can use this code:

$('#id_select').chosen({
    width: '100%', 
    create_option: true, 
    persistent_create_option: true, 
    skip_no_results: true
});

jsfiddle link: https://jsfiddle.net/n4nrqtek/

I found a solution multiple select

var str_array = ['css','html'];
$("#id_select").val(str_array).trigger("chosen:updated");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!