简体   繁体   中英

pushing values in array in hidden field

I had a following jquery code where i need to push values in a hidden field using comma if there are multiple items added.

i am using this code for pushing values but i am confused where and how do i add value in the hidden field so i can use the chosen value

jquery code

function initializeAutocomplete(obj){
    obj.autocomplete({
        source: function (request, response) {
            var values = [];
            for(var x = 0;x < predifined_cources.length;x++){
                if(predifined_cources[x].text.indexOf(request.term)>-1)
                    values.push({"label":predifined_cources[x].text, "value":predifined_cources[x].id+"~YES"}); 
            }
            if(values.length==0){
                $.post("customers.cfm",{"term":request.term})
                .done(function(data){
                    try{
                        var obj = $.parseJSON(data),
                        values = [];
                        for(var x = 0; x < obj.length; x++){
                            values.push({"label":obj[x].text, "value":obj[x].id});
                        }
                        response(values);
                    }catch(e){
                    }
                })
                .fail(function(e){
                });
            }
            else
                response(values);
        },
        change: function(event, ui) {
            if (!ui.item) {
                $(this).next().val('');
            } 
        },
        select: function(event, ui) {
            $(this).next().val(ui.item.value);
            ui.item.value = ui.item.label;
        }
    });
}
initializeAutocomplete($('[selectCustomer]').first());

html code:

<input selectCustomer name="customer_name" class="form-control" id="customer_name_select" value="" placeholder="Select Customer..." data-rule-required="true" data-msg-required="Choose Customer"/>
                                <input type="hidden" value=""/>

As soon as the loop is complete that creates the array you would convert the array to string and set the value of the field

You could use JSON to keep array structure

$('#customer_name_select').val( JSON.stringify(array));

Or for comma separated string use Array.prototype.join()

$('#customer_name_select').val( array.join());

You can use the jQuery data -function. It allows you to add objects to DOM - elements without having to convert them manually to a string. It is only sufficient if you need the data only on client - side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM