Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click() method not behaving as expected

I wrote a function that, on clicking a certain element, would replace a div with a hidden span. When I had the event handler in the "onclick=" attr in the tag, the function worked fine. But then I tried to get "fancy" and replace onclick attr with jQuery's .click() method. Now, when I try to use it on the page, nothing but a clunk -- nothing happens.

However, if I execute the exact same code in Chrome's js console, it works great. Here is my js:

$("a#delete").click(function () {
    $("a#delete").replaceWith($("span.hconf").attr("style", "none"))
});

Here is the relevant html (the is inside a div, the is outside):

<a class='modify' id="delete" u="{{ i.id }}" href='#'>delete</a>
<span class='hconf' style="display:none;">Are you sure? <a class='confirm' id='del_conf_true' onclick='deltrue();' href='#'>yes</a> | <a class='confirm' id='del_conf_false' href='#'>no</a></span>

I know I can change the second $("a#delete") with the "this" keyword, but I am leaving that undone now as I'm not sure if that's part of the problem. I am a newcomer to js/jQuery.

like image 983
mattdeboard Avatar asked Nov 18 '25 00:11

mattdeboard


1 Answers

Ready it:

$(document).ready(function() {
    $("a#delete").click(function () {
        $(this).replaceWith($("span.hconf").attr("style", "display:none"));
    });
});

...and don't you mean style="display:none"? You can just as easily use .hide():

$("span.hconf").hide();

And lastly, it is pointless using a filtering tag on an ID selector. Just do $("#delete"), it is both shorter and quicker.

like image 98
karim79 Avatar answered Nov 20 '25 16:11

karim79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!