Html: For Select multiple, only one value is submitted but .val() returns array of two values
Asked Answered
A

3

11

When rendering the page, the val() of a multiple select is set with a single value. For example, $("#my_select_box").val(1); Then the user selects an additional value in the multiple select box.

When the form is submitted, only the newly selected value is submitted and not the previously set one. Whereas while debugging in Firefox, the .val() function returns an array of two values (both the previous one and the newly selected one). Why does this happen?

Austen answered 23/8, 2011 at 0:43 Comment(0)
S
37

If you are programming in PHP, the problem lies there. When using multiselect inputs, PHP requires you to have an empty pair of brackets after input name. For example:

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

rather than just

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

If you can't or won't do this (perhaps you don't have access to the underlying HTML), then you can alternatively capture the POST data like this:

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

And you'll see a string like this that you can use:

select=one&select=two&select=three&button=submit
Salpa answered 21/1, 2013 at 1:47 Comment(1)
If you want to convert that last string into a workable array, parse_str() will not work, as it will throw out the duplicate elements. There is a simple function named proper_parse_str() that will work, available at php.net/manual/en/function.parse-str.php#76792Salpa
W
3

Well, without code we can't be sure. But when you want multiple params to be passed in you have to give a name value of that input the [ ] brackets. Ex. "name[]" so in order for the server to know that there are in fact two values.

Wizard answered 23/8, 2011 at 0:56 Comment(0)
C
0

Hard to tell what to do without the code.

However, if you want both the option that you marked selected and another that was selected, you could access them as follows:

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

and

option:selected for the one chosen 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/

Croesus answered 23/8, 2011 at 1:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.