The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.
HTML
To access id use 'on' as your div is dynamically generated:
$(document).ready(function() {
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
});
Firstly, you have jQuery - you should use that to register your event handlers instead of using obsolete, error prone inline event handlers.
Secondly, your button handler is inside #formarea
and so is also triggering the click handler since the button's parent has no ID. This is probably not desired.
Thirdly, your event handlers need to be delegated because you're trying to catch events on dynamically added elements.
So, remove the onclick
attribute and add this:
$('#formarea button').on('click', addRow);
$('#formarea').on('click', '.form_row', function() { // delegated, for dynamic rows
console.log(this.id); // NB: not $(this).attr('id') !!
});
function addRow(ev) {
// unmodified
}
See http://jsfiddle.net/alnitak/aZTbA/
Ok, I think I understand what you are missing. You are trying to log the ID
after adding a row using add_row
function,
.form_row
is added dynamically to the DOM. So when executing $('.form_row').click(
, there is no .form_row
to bind the handler. The below way of using .on
method binds the handler to #form_area
and executes the handler only when the click event is from .form_row
$('#form_area').on('click', '.form_row', function () {
console.log(this.id);
});
$('#form_area div')
selects the div
inside the div #form_area
which doesn't have an ID
Below comment in html shows which div is selected,
<div id="form_area">
<div> <!-- $('#form_area div') selects this div-->
<button onclick="return add_row();" style="width:100%;">Add Row</button>
</div>
</div>
Try console.log($('#form_area div').attr('id'));