HTML get name of select option

I want to get name of the select option, but it appears to be blank, demonstrated in codepen. Getting value works though, so I want to get name in the same manner.

As you can see, name is different for each option so it cannot be added in the <select>, and I want to avoid using data- as it would require hard-coding this edge case into re-usable functions.

http://codepen.io/anon/pen/wJzQWW?editors=1010

<select>
  <option name="" value="" selected>Or</option>
  <option name="tags" value="123">And</option>
  <option name="not-tags" value="123">Not</option>
</select>

Answers 1

  • $(input).find(":selected") will get you the selected option, from there you can use val() and attr() to get the values

        function parseInputs(jqElem, selector = ':input', payload = '') {
          for (let input of $(jqElem).find(selector)) {
            const value = $(input).find(":selected").val();
            const name = $(input).find(":selected").attr("name");
            if (!value) {
              continue
            }
            payload += `&${name}=${value}`;
          }
          return payload.substring(1);
       }
    

Related Articles