0

I am using jQuery to add select in each row of a table. The selects are assigned a class name.

Now, I need to get the value of the select on change using this dynamically assigned class name.

$select = $('<select class="medName"></select>');

for(var i = 0;i < tmp.length-1; i++){
                $option = $('<option>'+tmp[i]+'</option>');
                $select.append($option);
}

Here tmp contains data fetched from backend.

Finally,

    var $row = $('<tr></tr>');
    var $data1 = $('<td></td>');
    var $data2 = $('<td></td>');
    var $data3 = $('<td></td>');
    var $data4 = $('<td></td>');

    //alert($select.html());

    $data1.append($select);
    $data2.append($type);
    $data3.append($text);
    $data4.append($label);

    $row.append($data1);
    $row.append($data2);
    $row.append($data3);
    $row.append($data4);

    $row.insertAfter('#CashMemoBody');

This works perfectly fine.

Now when I do,

$('.medName').on('change', function (e) {
        var val = $(this).find('option :selected').html();
        alert(val);
});

I do not even get an alert.

Inspect Element shows, that the classes are properly assigned.

Whats going wrong ?

Here the problem is NOT only dynamic binding, but also getting the value of the selected option. None of the provided solutions seem to work here. Hence the question.

Ankita Singh
  • 21
  • 1
  • 5

1 Answers1

3

It should be-

$(document).on('change','.medName',function(){
  var val = $('option:selected',this).val()
  alert(val);
});

Because .medName is dynamically created

Manoz
  • 6,507
  • 13
  • 68
  • 114