Dima Chebotaru Dima Chebotaru - 8 months ago 43
HTML Question

Add "selected" attr to options in different select "tag"

I have one "table" with sizes. And want to add attr "selected" to "option" in all "selects in the document.

<select name="Size" id="size_11">
<option value="37" selected="">37</option>
<option value="37.5">37.5</option>
<option value="38">38.5</option>
<option value="39">39</option>
<option value="40">40</option>
<option value="40.5">40.5</option>
<option value="41">41</option>
<option value="41.5">41.5</option>
<option value="42">42</option>
<option value="43">43</option>
<option value="43.5">43.5</option>
<option value="44.5">44.5</option>
<option value="45">45</option>
<option value="45.5">45.5</option>
<option value="46">46</option>
<option value="46.5">46.5</option>
<option value="47">47</option>
<option value="48">48</option>
<option value="48.5">48.5</option>

This works:

$('#modal_sizes tr').click(function() {
$('option').removeAttr('selected').eq($(this).index()).attr('selected', ' ');

But it works only with the first "select" in the document Removing attr "selected" from all "option", but adding it only to an "option"s in first "select".

Answer Source

use option:nth-child in the selector

$('#modal_sizes tr').click(function() {
  $('select > option').removeAttr('selected');
  $('select > option:nth-child('+$(this).index()+')').attr('selected', ' ');