Reputation: 1995
I have used Event binding on dynamically created elements? and Get changed value from <select> using jQuery to get to where I am now.
I am creating a Select dropdown dynamically and would like to capture the selected item.
My code is:
$(document).on('click', '#programDetailTablebody button[name="addPDRow"]', function(e) {
e.preventDefault();
var newRows = "";
newRows += "<tr><td class='button'><button type='button' name='addPDRow' class = 'buttonFront'><span class='glyphicon glyphicon-plus'></span></button></td>";
newRows += "<td class='keyvalue'><input class='timeWidth timeClass pdValue' name='timeInput' value='07:00'></input></td>"; //Time
newRows += "<td class='keyvalue'><select class='form-control activityTypeWidth activityTypeClass pdValue' name='activityTypeInput'>" //Activity Type
newRows += "<option value='' disabled selected>Select Activity Type</option>" + activityTypeOptions + "</select>"
newRows += "<td class='keyvalue'><select class='form-control activityWidth activityClass pdValue' name='activityInput'>" //Activity
newRows += "<option value='' disabled selected>Select Activity</option>" + activityOptions + "</select>"
newRows += "<td class='keyvalue'><input class='equipmentClass pdValue' name='equipmentInput'></input></td>";//Equip. Needed
newRows += "<td class='keyvalue'><input class='awardClass pdValue' name='awardInput'></input></td>";//Award
newRows += "<td class='keyvalue'><input class='leadersClass pdValue' name='leadersInput'></input></td>";//Leaders
newRows += "<td class='button'><button type='button' name='removePDRow' class = 'buttonFront'><span class='glyphicon glyphicon-minus'></span></button></td></tr>";
$(newRows).insertAfter($(this).closest('tr'));
});
$("select[name='activityTypeInput']").on( 'change', 'option', function (e) {
e.preventDefault();
alert("Changed");
var activityType = $(this).val();
alert(activityType);
});
This is the page:
The alerts are not triggered when I select an option and there are no errors in the console.
Upvotes: 0
Views: 1062
Reputation: 950
As in the accepted answer in the link you provided, you can use event binding on the existing parent element (in this case, for example, you can use #programDetailTablebody).
So instead of using
$("select[name='activityTypeInput']").on( 'change', 'option', function (e) { ... }
You an use
$('#programDetailTablebody').on( 'change', "select[name='activityTypeInput']", function (e) { ... }
Upvotes: 1