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

Vincent picture Vincent · Jul 15, 2009 · Viewed 21.8k times · Source

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.

Answer

Edward Dale picture Edward Dale · Jul 15, 2009

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.