Jack
Jack

Reputation: 37

Get text from dynamic select option

I have more than one select option, i want to write text car or motorcycle on .texts

This a few dynamic select option

<td>

<select id="area-0">
  <option value="1">Car</option>
  <option value="2">Motorcycle</option>
</select>
</td>

<td class="texts"></td>

<td>
    <select id="area-1">
      <option value="1">Car</option>
      <option value="2">Motorcycle</option>
    </select>
</td>

<td class="texts"></td>

this my script

$('select[id^=area]').change(function(){
    var text_t = $(this option:selected).text();
  $(this).parent().next().html(text_t);

});

How can i place car or motorcycle on .texts

Upvotes: 1

Views: 1545

Answers (2)

Rayon
Rayon

Reputation: 36609

You have invalid html. Wrap it in table -> tr

$(this option:selected) is not a valid selector. Use $(this).find('option:selected')

$('select[id^=area]').change(function() {
  var text_t = $(this).find('option:selected').text();
  $(this).parent().next().html(text_t);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select id="area-0">
        <option value="1">Car</option>
        <option value="2">Motorcycle</option>
      </select>
    </td>
    <td class="texts"></td>
    <td>
      <select id="area-1">
        <option value="1">Car</option>
        <option value="2">Motorcycle</option>
      </select>
    </td>
    <td class="texts"></td>
  </tr>
</table>

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use .find() method to get the selected option's text. As per current implementation you must be getting syntax error.

var text_t = $(this).find('option:selected').text();

instead of

var text_t = $(this option:selected).text();

Upvotes: 0

Related Questions