How to hide a dom element after creating it on the fly using jQuery?

I am trying to create a form in which users can add a text field by clicking the "add parameter" button. They can also delete added fields via the delete 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 the add_option button, a new text field and delete_link appear. But when you click on the "delete_link" created by jQuery, the browser follows the link instead of launching the clicked popup.

How to hide a dom element after creating it on the fly using jQuery?

+4
source share
3 answers

I would use a delegate because it uses fewer bubbles:

 $(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")); }); 
+6
source

Try attaching a handler for <a> to "live"

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

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

0
source

I don't understand why you use <a> as a button to execute a function in jQuery. You have all the tools you need right within the framework to completely circumvent the tattered HTML traditions.

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

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

Source: https://habr.com/ru/post/1305851/


All Articles