views:

46

answers:

3

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. My code looks like this :

$(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;
          });
  });

This code is not working : 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". Any idea ? Thanks !

A: 

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.

Pointy
+5  A: 

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"));
});
c0mrade
I did not know the delegate function, I'am quite new in Jquery programming. Thanks, it solved my problem !
ismaelsow
A: 

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();
}
dclowd9901