Erm, why this don`t work, iv used similar code like this for my site many times..butnow dont work..
HTML
<div><span>a</span><input type='hidden' /> <input type='button' onClick='Remove(event)' />
JQuery
function Remove(e){
e.preventDefault();
$(this).closest('div').remove();
}
Looks like $(this) is not my button. I tested with alert($(this).val()) and nothing heppend.
Erm, why this don`t work, iv used similar code like this for my site many times..butnow dont work..
HTML
<div><span>a</span><input type='hidden' /> <input type='button' onClick='Remove(event)' />
JQuery
function Remove(e){
e.preventDefault();
$(this).closest('div').remove();
}
Looks like $(this) is not my button. I tested with alert($(this).val()) and nothing heppend.
Share Improve this question asked Oct 4, 2012 at 18:25 Novkovski Stevo BatoNovkovski Stevo Bato 1,0432 gold badges24 silver badges56 bronze badges 3- 1 Why don't you bind the event handler with jQuery since you're already using it? That would make things much easier. – James Allardice Commented Oct 4, 2012 at 18:26
- My divs are created from clientside and serverside too. Its much easy to add onclick function instead to unbind-rebind all on new item, no? – Novkovski Stevo Bato Commented Oct 4, 2012 at 18:28
- @NovkovskiStevoBato you can use delegated events if you are worried about it being created dynamically – Selvakumar Arumugam Commented Oct 4, 2012 at 18:29
2 Answers
Reset to default 4How about adding a class to the button element and bind a handler to the button
<div>
<span>a</span>
<input type='hidden' />
<input type='button' class'removeDiv' />
Code:
$(function () {
$('.removeDiv').click (function () {
$(this).parent().remove();
// As I see the input is direct child of the div
});
});
My divs are created from clientside and serverside too. Its much easy to add onclick function instead to unbind-rebind all on new item, no?
In such cases you can use delegated events. See below,
$(function () {
//Replace document with any closest container that is available on load.
$(document).on('click', '.removeDiv', function () {
$(this).parent().remove();
// As I see the input is direct child of the div
});
});
This should work!
HTML
<div><span>a</span><input type='hidden' /> <input type='button' onClick='Remove(this)' />
JQuery
function Remove(obj){
$(obj).closest('div').remove();
}