Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST empty <select .. multiple> HTML elements if empty?

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.

like image 765
Vincent Avatar asked Jul 15 '09 15:07

Vincent


3 Answers

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.

like image 179
Edward Dale Avatar answered Nov 03 '22 22:11

Edward Dale


If you add a hidden input before the multiple select element, it will send the hidden input value if none of the multiple select items have been selected. As soon as you select an option though, that selected value is used instead.

This way I was able to distinguish 2 different scenarios in Laravel/php, being:

  • Set all myitems to empty (requiring the hidden input, so PHP receives an empty string for myitems)
  • Update other properties of the model without touching myitems (so excluding any myitems input form the form. PHP will not receive the myitems key)

Sample code:

<input type="hidden" name="myitems" value="" />
<select name="myitems[]" multiple>
  <option value="1">Foo</option>
  <option value="2">Bar</option>
</select>
like image 16
Flame Avatar answered Nov 04 '22 00:11

Flame


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();
like image 12
Matt Bridges Avatar answered Nov 03 '22 22:11

Matt Bridges