Html: for the Select Multiple parameter, only one value is sent, but .val () returns an array of two values

When rendering a page, the val() parameter for multiple selection is set to a single value. For example, $("#my_select_box").val(1); The user then selects an additional value in the multiple selection field.

When a form is submitted, only the newly selected value is submitted, not the previously set value. If, during debugging in Firefox, the .val() function returns an array of two values โ€‹โ€‹(both the previous and the new). Why is this happening?

+7
source share
3 answers

If you are programming in PHP, the problem is there. When using multi-selective inputs, PHP requires an empty pair of brackets after the input name. For example:

 <select name="select[]" multiple="multiple"> 

not just

 <select name="select" multiple="multiple"> 

If you donโ€™t or donโ€™t (perhaps you donโ€™t have access to the basic HTML), you can also write POST data as follows:

 $data_from_post = file_get_contents("php://input"); var_dump($data_from_post); 

And you will see a line that you can use:

 select=one&select=two&select=three&button=submit 
+18
source

Well, without code, we cannot be sure. But when you need to pass a few parameters, you must specify a name that introduces the brackets []. Ex. "name []" so that the server knows that there are actually two values.

+2
source

It's hard to say what to do without code.

However, if you want both the option you checked selected and the other that was selected, you can access them as follows:

option[selected="selected"] for the one you installed

and

option:selected for the selection selected by the user

So something like this ...

 $('#submit').click(function(){ var s = $('#my_select_box option[selected="selected"]').val(); var t = $('#my_select_box option:selected').val(); alert("Set: " + s + ", Chosen: " + t); }); 

Example: http://jsfiddle.net/jasongennaro/pZesG/1/

0
source

All Articles