Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 928
Maddy.Shik Avatar asked Aug 23 '11 00:08

Maddy.Shik


2 Answers

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
like image 134
pbarney Avatar answered Oct 03 '22 23:10

pbarney


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.

like image 39
HaloZero Avatar answered Oct 04 '22 00:10

HaloZero