dimanche 12 juin 2016

select all form elements that are selected as well as non-selectable form elements


I have markup that looks something like this:

<form>
  <select class="form-control" id="follower_id" name="event[task_followers_attributes][0][follower_id]">
    <option value=""></option>
    <option data-typeahead-associated-id="1" value="1" selected>Administrator</option>
    <option data-typeahead-associated-id="2" value="2">Marketing Guy</option>
  </select>
  <input type="hidden" data-typeahead-associated-id="2" name="event[followers_attributes][1][id]" value="2">  
</form>

I want to find all form elements who have the data attribute "data-typeahead-associated-id". However, if the form element is a form element that is selectable (e.g. select, radio button), then I only want the data-typeahead-associated-id for the one that is selected. Since input fields do not have multiple options, I want all input fields that match the "data-typeahead-associated-id" attribute.

Therefore, in the above example I want the select option with value 1, not 2. And I also want the input field with value 2.

I thought up this solution, which appears to be working:

$('form').find('[data-typeahead-associated-id]').not('option:not(:selected),input[type="radio"]:not(:checked),input[type="checkbox"]:not(:checked)')

But is there a more stable, elegant solution?


Aucun commentaire:

Enregistrer un commentaire