Search code examples
javascriptjqueryjquery-ui-multiselect

How can I put selected value of jquery multiselect dropdown into a hidden element's id


How can I put selected value of jquery multiselect dropdown into a hidden element's id? I need that id be an array so I can get the selected values of the multiselect into that.

What I tried is:

$( "#Myselect" ).change(function(){
    var str = "";
    $( "select option:selected" ).each(function() {
        str += $( this ).val() + " ";
    });
    document.getElementById("objecttype").value = str; 
}).trigger( "change" );

<html:hidden styleId="objecttype" property="objecttype" name="Myobjecttype"/>

but objecttype is just an id and isn't an array!


Solution

  • I assume you want this hidden field to be posted somewhere and used later on (server-side or whatever). Take a look at this Fiddle: http://jsfiddle.net/hm71689h/ it is roughly what you wanted.

    Take into account what Haxxxton just said: you're joining the values using a delimiter (in this example a comma by default). You need to split that value into a new array later on.

    Also, in your code-sample, you're referring to the hidden field using: document.getElementById("objecttype") But you did not use an identifier, you used a name. Although you might think it should be the same, an ID is not the same as the name of an element.