jquery serialize and multi select dropdown

2019-01-11 13:17发布

I have been using the jquery serialize() function to serialize the values of a form and submit it via ajax

like for e.g. if the form name and id is factoryUsers

var data=$("#factoryUsers").serialize();

Now this works fine for forms that have text fields, text areas, simple drop downs etc. But when I have a multiple dropdown , things go awry for e.g. if I have a dropdown of the type

<select size="5" id="factoryUsers" name="factoryUsers" multiple="multiple">

the serialize doesn't work correctly anymore. so if I select 3 users I get a query string like

factoryUsers=5&factoryUsers=23&factoryUsers=11

changing the select to array type doesn't help either factoryUsers[]

Any idea or help how to get this working correctly would be great.

6条回答
家丑人穷心不美
2楼-- · 2019-01-11 13:56

You can use the PHP function

parse_str($_POST)

This function seems to be an extract function. After you run this, you can access a var named $factoryUsers, and this var is an array $factoryUsers[n].

查看更多
何必那么认真
3楼-- · 2019-01-11 13:58

The string output you've described above is the correct way of submitting multiple values for forms with the same name over HTTP, so jQuery is working correctly. It's up to you to handle how this is processed on the server-side, which is then dependent on what language you are using.

If you're using PHP, this may help: http://bytes.com/topic/php/answers/12267-how-php-_post-gets-multiple-values-html-form

Can you tell us what language you're using?

查看更多
叼着烟拽天下
4楼-- · 2019-01-11 13:59

All you need is change name="factoryUsers" to name="factoryUsers[]" PHP will treat it as array.

查看更多
smile是对你的礼貌
5楼-- · 2019-01-11 14:09

Just try it to get value with val()

data='factoryUsers=' + $("#factoryUsers").val();

It will give you the values with comma seperate.

factoryUsers=1,2,4

If this item is one of your form. Then try to add the value of item end of the serialize. Example:

data= f.serialize() + '&factoryUsers=' + $('#factoryUsers').val();

Since, the item written twice into the request, the last value will be valid in controller.

查看更多
叼着烟拽天下
6楼-- · 2019-01-11 14:11

Your elements name must be array type factoryUsers[] Change your code this:

<select size="5" id="factoryUsers" name="factoryUsers[]" multiple="multiple">

Thanks...

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-11 14:21

Try changing the name of the select to factoryUsers[]. That way you can loop through it in your backend.

查看更多
登录 后发表回答