TM Prananditha TM Prananditha - 1 year ago 101
Javascript Question

How to get Selected Option ID (with AddRow Datatable)

I'm trying to get an Selected Option ID. in single row, it works. but if I add new row(s), the function only work in 1st row. why? Can you help me?



$("#hobby").on('change', function (){
alert($(this).find('option:selected').attr("id"));

});

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<table id="dataTable" border=0>
<tr>
<td><input type="checkbox" name="chkstruktur[]" checked></td>
<td>
<select name="hobby" width="100px" id="hobby" >
<option id='1' value="Soccer">Soccer</option>
<option id='2' value="Running">Running</option>
<option id='3' value="Karate">Karate</option>
<option id='4' value="Bowling">Bowling</option>
</select>
</td>
</tr>
<tr>
<td><input type="checkbox" name="chkstruktur[]" checked></td>
<td>
<select name="hobby" width="100px" id="hobby" >
<option id='1' value="Soccer">Soccer</option>
<option id='2' value="Running">Running</option>
<option id='3' value="Karate">Karate</option>
<option id='4' value="Bowling">Bowling</option>
</select>
</td>
</tr>
</table>




Answer Source

id in a html page has to be unique always. Please change your id to class attribute with same name and bind event to class as $('.hobby'). Rest everything's fine.

$(".hobby").on('change', function() {
  alert($(this).find('option:selected').attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<table id="dataTable" border=0>
  <tr>
<td>
  <input type="checkbox" name="chkstruktur[]" checked>
</td>
<td>
  <select name="hobby" width="100px" class="hobby">
    <option id='1' value="Soccer">Soccer</option>
    <option id='2' value="Running">Running</option>
    <option id='3' value="Karate">Karate</option>
    <option id='4' value="Bowling">Bowling</option>
  </select>
</td>
  </tr>
  <tr>
<td>
  <input type="checkbox" name="chkstruktur[]" checked>
</td>
<td>
  <select name="hobby" width="100px" class="hobby">
    <option id='1' value="Soccer">Soccer</option>
    <option id='2' value="Running">Running</option>
    <option id='3' value="Karate">Karate</option>
    <option id='4' value="Bowling">Bowling</option>
  </select>
</td>
  </tr>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download