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

1.6k views Asked by At

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!

2

There are 2 answers

0
Leon On BEST ANSWER

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.

0
Sergey Narozhny On

I think you need smth like this:

HTML:

<select name="choice" multiple id="mySelect">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<input type="hidden" name="myObjecttype" />  

JS:

$('#mySelect').change(function(){
      //brand new array each time
    var foo = [];
      //fills the array
    foo = $("option:selected", this).map(function(){ return $(this).val() }).get();
      //fills input with vals, as strings of course
    $("input[name='myObjecttype']").val(foo);
      //logs an array, if needed
    console.log($("input[name='myObjecttype']").val().split(','));
});  

Don't forget hidden input can't store array-/object- data, only strings. But you can easily make array.

See working jsfiddle: http://jsfiddle.net/sfvx5Loj/1/