1

Onchange function is not working in Jquery.

In my page i need to add select tag when i click the add button.

My code is here

Using Below code to add a new select tag. This code is working fine.

var counter =1;    
var newrow = $(document.createElement('tr')).attr("id", 'newgroup' + counter);  
var httttm = "";    
httttm += "<td><select name='input_field[]' class='form-control' ><option value=''>Select</option><option value='input'>Text</option><option value='option'>Option</option></select></td></td>";        
newrow.after().html(httttm);
newrow.appendTo("#newgroup");
counter++;

Following code is used to get the option value from the select tag. Normally below code is working fine. But when i add the new select tag using above code onchange function is not working.

 $('select').change(function (){
    var selvalue = $(this).val();           
    if(selvalue == "option")    {       
        alert("hai");
    }
 });    
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
Mukhila Asokan
  • 565
  • 2
  • 8
  • 24

2 Answers2

2

Currently, You are using direct event binding, Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

As you are creating elements dynamically, use Event Delegation using .on() delegated-events approach.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

i.e.

$(staticParentElement).on('event','selector',callback_function)

Example

$('#newgroup').on('change', "select", function(){
    var selvalue = $(this).val();           
    if(selvalue == "option")    {       
        alert("hai");
    }
});
Satpal
  • 129,808
  • 12
  • 152
  • 166
1

Try this : You need to delegate event using .on() to bind change event for dynamically generated elements

$(document).on("change", 'select',function (){
    var selvalue = $(this).val();           
    if(selvalue == "option")    {       
        alert("hai");
    }
 });
Bhushan Kawadkar
  • 27,908
  • 5
  • 34
  • 57