jquery-clone

get select text with jquery in table


i have a table with this select:

<tr class="tr_clone">
    <td>
      <select style="width:200px" name="itens[]" class="itemname">
        <option value="0"></option>
        <option value="1">Item A</option>
        <option value="2">Item B</option>
        <option value="3">Item C</option>
    </td> 

in jquery, I am trying to get the text of the selected item (Item A when 1 is selected). I am then putting this value to another text box, (named 'note'). I can put the index value but not the text of the select.

$("table").on('change', '.itemname', function() { 
   var prtCont = $(this).parent().parent();
    var code =  prtCont.find('.itemname').val();
  prtCont.find('.note').val(code);
});

what should I change in my jquery?


Solution

  • Well, 1st close the select tag.

    <tr class="tr_clone">
    <td>
      <select style="width:200px" name="itens[]" class="itemname">
        <option value="0"></option>
        <option value="1">Item A</option>
        <option value="2">Item B</option>
        <option value="3">Item C</option>
      </select>
    </td> 
    </tr> 
    

    To get the text of the selected item you can do:

    $('.itemname option:selected').html()
    

    Your jQuery is a little confuse, for me is better:

    $('.itemname').on('change' , function() {
      var prtCont = $(this).parent().parent(); 
       code = $(this).val();  // Get the value
       text = $('.itemname option:selected').html(); // Get the text
       prtCont.find('.note').val(code + '   ' +text);
    });