Sahi R. Repswal Sahi R. Repswal - 9 months ago 47
Javascript Question

Jquery Call onchange function on dynamically created dropdown

How to Call onchange function on dynamically created dropdown. Code is like below :
HTML Code :

<img id="addColumn" src="images/icons/panel_add.gif" alt="Add Column" onclick="addColumnDynamically('q_123_456_789')"/>
<div class = "q_123_456_789"></div>


Javascript

function addColumnDynamically(currentObjId){
maxRepeatedColumnSeq = maxRepeatedColumnSeq+1;
var dropDownIdStr = currentObjId;
dropDownIdStr = dropDownIdStr.substring(dropDownIdStr.indexOf("_") + 1);;
dropDownIdStr = "q_drop_"+dropDownIdStr+"_"+maxRepeatedColumnSeq;
alert("idStr........"+dropDownIdStr);
$("."+currentObjId).append('<div class="Content22">\
<br>\
<input class="input numberElement" type="text" style="width: 25%" id='+currentObjId+"_"+maxRepeatedColumnSeq+'>\
<select class="selectStyle1" style="width: 25%" id='+dropDownIdStr+'<option value=""></option><option value=""></option><option value="Hours">Hours</option><option value="Days">Days</option><option value="Weeks">Weeks</option><option value="Months">Months</option><option value="Years">Years</option> >\
<img src="images/icons/panel_remove.gif" onclick="removeColumn(this)">\
<br>\
</div>');
$('#'+currentObjId+"_"+maxRepeatedColumnSeq).on('blur', function () {
alert("Hiii....");
});
alert("Hiii.."+dropDownIdStr);
$('#'+dropDownIdStr).on('change', function () {
alert("getElementById...."+document.getElementById(dropDownIdStr));
});
}


onblur function is calling but onchange is not calling. How can i do this ?

Answer Source

Take a look at the code: You missed the closing ">" and the closing "</select>"

$(document).ready(function(){
	$(document).on('click', '#addColumn', function(evt){ addColumnDynamically('q_123_456_789')} );
  
})

function addColumnDynamically(currentObjId){
var maxRepeatedColumnSeq = maxRepeatedColumnSeq+1;
var dropDownIdStr = currentObjId;
dropDownIdStr = dropDownIdStr.substring(dropDownIdStr.indexOf("_") + 1);;
dropDownIdStr = "q_drop_"+dropDownIdStr+"_"+maxRepeatedColumnSeq;
alert("idStr........"+dropDownIdStr);
$("."+currentObjId).append('<div class="Content22">\
        <br>\
        <input class="input numberElement" type="text" style="width: 25%" id='+currentObjId+"_"+maxRepeatedColumnSeq+'>\
        <select class="selectStyle1" style="width: 25%" id='+dropDownIdStr+'><option value=""></option><option value=""></option><option value="Hours">Hours</option><option value="Days">Days</option><option value="Weeks">Weeks</option><option value="Months">Months</option><option value="Years">Years</option></select>\
        <img src="images/icons/panel_remove.gif" onclick="removeColumn(this)">\
        <br>\
    </div>');

alert("Hiii.."+dropDownIdStr);
$('#'+dropDownIdStr).on('change', function () {
alert("getElementById...."+document.getElementById(dropDownIdStr));
});
}