marioizquierdo / jquery.serializeJSON

Serialize an HTML Form to a JavaScript Object, supporting nested attributes and arrays.
MIT License
1.71k stars 433 forks source link

use :skip in <select> option field #90

Closed randallmlough closed 5 years ago

randallmlough commented 5 years ago

So I'm trying to figure out a way to include an "other" field in a select element that can be skipped when selected. I'm dynamically adding an input field when an "other" option is chosen that includes the appropriate name value, unfortunately, I haven't been able to figure out a way for the option value to be skipped if selected.

Here's an example

<select name="options[][name]">
  <option value="foo">foo</option>
  <option value="bar">bar</option>
  <option value=":skip" class="other">other</option> 
</select>
marioizquierdo commented 5 years ago

Let me make sure I understand your question. So, what you would want for the example select element is to appear in the serialized object with the selected option, except if that option is the "other". For example:

$('select').serializeJSON();
// => {"options": [{"name": "foo"}]} // if option "foo" is selected
// => {"options": [{"name": "bar"}]} // if option "bar" is selected
// => {"options": []} // if option "other" is selected

There is no standard way to do this, because the name attribute is meant for the key and can only be specified in the select element (not in the options). The options are for the selected value.

But you can use the option skipFalsyValuesForFields or the HTML attribute data-skip-falsy. Just make sure to use an empty value on the "other" option:

<select name="options[][name]" data-skip-falsy="true">
  <option value="foo">foo</option>
  <option value="bar">bar</option>
  <option value="" class="other">other</option> 
</select>