ismaelsow
ismaelsow

Reputation: 757

How to hide a dom element after creating it on the fly with JQuery?

I am trying to build a form where users can add a text field by clicking on a "add option" button. They can also remove added fields by a "remove option" link created on the fly by Jquery, along with the text field.

JavaScript:

$(document).ready(function(){
    $("#add_option").click(function()
      {
        var form = $("form");
        var input_field = '<input type="text" />';
        var delete_link = '<a href="#">remove</a>';
        form.append(input_field + delete_link);

        return false;
    });

    $("a").click(function()
    {
        alert('clicked');
        return false;
    });
});

When I click on the "add_option" button, a new text field and the "delete_link" appear. But when clicking on the "delete_link" created by JQuery, the browser follows the link instead of launching a pop-up displaying "clicked".

How do I hide a dom element after creating it on the fly with JQuery?

Upvotes: 4

Views: 216

Answers (3)

dclowd9901
dclowd9901

Reputation: 6826

I don't get why you're using a <a> as a button to execute a function in jQuery. You have all the tools you need right in the framework to totally bypass well-worn traditions of HTML.

Just put a css cursor:pointer definition on the button you want to appear "clickable," add some text-decoration if that's your fancy, and then define your function with jQ:

$('.remove-button').live('click', function() {
    $(this).parent().remove();
}

Upvotes: 0

ant
ant

Reputation: 22948

I'd use delegate because its uses less bubbling :

$(document).delegate("a", "click", function(){
 alert('clicked');
});

EDIT , here is your code you need to change :

$(document).ready(function(){
       $("#add_option").click(function(){
               var form = $("form");
               var input_field = '<input type="text" />';
               input_field.addClass = "dynamic-texfield";
               var delete_link = '<a href="#" class="delete-trigger">remove</a>';
               form.append(input_field + delete_link);

               return false;
           });

Then comes the delegate part :

$(document).delegate(".delete-trigger", "click", function(){
     alert('ready to delete textfield with class' + $(".dynamic-texfield").attr("class"));
});

Upvotes: 6

Pointy
Pointy

Reputation: 413747

Try binding the handler for the <a> with "live"

$('a').live('click', function() { alert("clicked); });

You probably should qualify those <a> links with a class or something.

Upvotes: 0

Related Questions