Haymak3r
Haymak3r

Reputation: 1411

Setting selected value on dynamically generated rows with jQuery

I have a HTML grid which is being generated dynamically with row ID's of [row_X]. How can I use jQuery to iterate each row, locate child select controls and set the "selected" value?

<tr id="row_0">
  <td>
    <select class="selection">
         <option id='1' value='1'>A</option>
         <option id='2' value='2'>B</option>
         <option id='3' value='3'>C</option>
         <option id='4' value='4'>D</option>
         <option id='5' value='5'>E</option>
    </select>
  </td>
</tr>
<tr id="row_1">
  <td>
    <select class="selection">
         <option id='1' value='1'>A</option>
         <option id='2' value='2'>B</option>
         <option id='3' value='3'>C</option>
         <option id='4' value='4'>D</option>
         <option id='5' value='5'>E</option>
    </select>
  </td>
</tr>

Upvotes: 1

Views: 1428

Answers (2)

Steve Seeger
Steve Seeger

Reputation: 1477

$("#row_0").find( "select" ).val(1);

Refer to jQuery documentation for .val()

Upvotes: 1

guest271314
guest271314

Reputation: 1

Try changing id to class at option elements ; selector $("table tbody tr .selection") to select select elements ; utilize .each() to iterate select elements , use options.selectedIndex of select element with index of option to set selected option; e.g.; to select option having value "B" , set selectedIndex to 1

$(function() {
  $("table tbody tr .selection").each(function(index, el) {
    el.options.selectedIndex = 1
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
  <tbody>
    <tr class="row_0">
      <td>
        <select class="selection">
          <option class='1' value='1'>A</option>
          <option class='2' value='2'>B</option>
          <option class='3' value='3'>C</option>
          <option class='4' value='4'>D</option>
          <option class='5' value='5'>E</option>
        </select>
      </td>
    </tr>
    <tr class="row_1">
      <td>
        <select class="selection">
          <option class='1' value='1'>A</option>
          <option class='2' value='2'>B</option>
          <option class='3' value='3'>C</option>
          <option class='4' value='4'>D</option>
          <option class='5' value='5'>E</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Related Questions