Snap click to dynamic button using jQuery?

I want to create a button with a jQuery click on the fly. After the user is done and click the button, I want to destroy the button and click jQuery until I need to recreate it.

I'm not sure how to do this in jQuery. I know jQuery.live is an option, but I'm not sure if it will be better or worse than I want to do this.

+1
source share
3 answers

Live will work fine. If you want to avoid using it live, you can connect a new button when you add it to the DOM.

 function addNewButton() { $("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />"); $("#sweetness").click(function() { $(this).remove(); }); } 

With live, it becomes as follows:

 function addNewButton() { $("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />"); } $("#sweetness").live("click", function() { $(this).remove(); }); 
+2
source

That should work. Change the html in the lines accordingly:

  $('#targetdiv').append( $("<div>foobar</div>").click( function(evt) { $(this).remove(); })) 

Here's a demo site showing it in action.

0
source

Sorry to post such an old and answered question. I had a similar problem and this answer helped me, but they didn't deliver me. After trial and error ... Here is my practical solution for adding areas to a web page and deleting them. I use it with dynamic form fields, but your needs may vary.

Here is the part of the form in the static part of the page.

 <fieldset> <legend>Email-tauluun</legend> <a class="button_ajax email-add">Add new area</a> <p> <span class="email_original_area"> <label>Email: <input type="text" name="emails[]" id="email0" /> </label> </span> <!--Below we add some more areas--> <span id="email_add_area"></span> </p> </fieldset> 

Then we need some JavaScript features. They use jQuery.

 <script type="text/javascript"> //we need a counter for dynamic fields var cnt=0; $(document).ready(function(){ $('.email-add').click(function(){ cnt += 1; //let count... $('#email_add_area').append( '<span class="dynExtra"><br /><label>Email: ' + '<input type="text" name="emails[]" id="email' + cnt + '" /></label>' + '</span>' ); //this function creates a button for newly created area //must be done after the creation of the area addRemover(); }); }); function addRemover() { //appends remove button to the last created area $('<a class="button_ajax dynExtra-clear" name="dynExtra-clear">Remove area ' + cnt + '</a>').appendTo('#email_add_area'); //remove the clicked button and it previous sibling $('.dynExtra-clear').click(function(){ $(this).prev().remove(); $(this).remove(); }); } </script> 

Hope this helps someone and I haven't forgotten anything.

0
source

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


All Articles