shipra sharma shipra sharma - 4 months ago 6
Javascript Question

How to apply the .change function on the field which is created b the .change function of some other field?

This function is creating a process name(prc) field on changing part no(pno) field, now i want the process characteristic field on changing process name but .change function on process name is not working($('#prc').change(function(){}); this function is not working)

$('#pno').change(function(){
var partno=$("#pno option:selected" ).val();
$.ajax({
cache: false,
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array('controller'=>'Partconfs','action'=>'addpro'));?>',
data: ({partno:partno}),
success: function(result){
var pch=result.split('//');
var plen=pch.length;
var str="";
$('#fid').html('');
str='<tr><td><br><b>PROCESS NAME</b><br><br></td></tr><tr><td><select name="process_name" label="" id="prc" style="height:30px; margin-top:-5px; min-width:190px; width:auto;" ><option value="">Select any</option>';
$.each(pch,function(i,v){
str += '<option value="'+v+'">'+v+'</option>';
});
str +='</select></td></tr>';
$('#fid').append(str);
}
});
});

Answer

You either need to add the event listener directly after this line:

$('#fid').append(str);

when the node is ready to have event listeners attached, or you need to delegate the event from a parent node that is available before your new <select> is written to the DOM.

$('#fid').on('change', '#prc', function() {
   // do your stuff
});

This works by attaching the event to a valid component, but only firing when the selector of the changed element (beneath #fid) matches the selector '#prc'