How to POST empty <select .. multiple> HTML

2019-04-19 22:34发布

I have the following multi-select box in a HTML form, where user can select one or more option.

<select id="eng_0" name="eng_0[]" multiple size="3">
  <option value="Privilégier">Privilégier</option>
  <option value="Accepté">Accepté</option>
  <option value="Temporaire">Temporaire</option>
</select>

When the user selects no option, the form is POSTed to a PHP backend but it creates no empty array value for $_POST['eng_0'] as if the field was not even on the form.

This is kind of like the unchecked checkbox that is not submitted problem.

Is there any way to have it POST the select object even if there is no selected option? It can be in jQuery if that helps.

8条回答
淡お忘
2楼-- · 2019-04-19 22:42

Include <input type="hidden" name="yourfield" value="" /> to your form where the name is the same as for your multiple="multiple" select.


It is unfortunate that browsers do not send empty form parameters for multiple="multiple" selects like they do for non-multiple selects or a normal inputs.

Using a dummy value as proposed in the accepted answer is not a very clean solution.

(This question has nothing to do with jQuery)

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-19 22:44

If your form is generated dynamically, you could include a hidden form element with the same name that contains a dummy value. Then, just ignore the dummy value, if the value you get for that variable is ['dummy_value'] then you can treat that as meaning "nothing selected" in your code.

查看更多
4楼-- · 2019-04-19 22:47

You can add a - please select - entry and preselect it.

<select id="eng_0" name="eng_0[]" multiple size="3">
  <option value="nothing" selected="selected">- please select -</option>
  <option value="Privilégier">Privilégier</option>
  <option value="Accepté">Accepté</option>
  <option value="Temporaire">Temporaire</option>
</select>
查看更多
一纸荒年 Trace。
5楼-- · 2019-04-19 22:49

Add something like

    $("#field").change(function() {
      if (($("#field").val() || []) == "") $("form").append("<input type='hidden' name='field' value=''>");
    });

查看更多
【Aperson】
6楼-- · 2019-04-19 22:52

if there is no $_POST, Post an empty string (nothing) is absolutely the most simple solution.

Here my solution for a Form with a <select name="related[]" multiple>

just add the following line in the php section that handles the storing of your form:

if (!isset($_POST['related'])) $_POST['related']="";
查看更多
我只想做你的唯一
7楼-- · 2019-04-19 22:54

Is there a reason you can't treat the situation where the array isn't set as if it was sent with no contents?

if (!isset($_POST['eng_0']))
    $_POST['eng_0'] = array();

EDIT:

Add a hidden field whenever the multiple select is present in your form:

<input type="hidden" name="eng_0_exists" value="1"/>

Then check:

if (!isset($_POST['eng_0']) && isset($_POST['eng_0_exists']))
    $_POST['eng_0'] = array();
查看更多
登录 后发表回答