I want to create a button that has a jQuery click on the fly. After the user is done and hit the button I want to destroy the button and the jQuery click until a time I need it
This should work. Change html in strings appropriately:
$('#targetdiv').append( $("<div>foobar</div>").click( function(evt) { $(this).remove(); }))
Here's a demo site showing it in action.
Live would work just fine. If you'd like to avoid using live, you can wire up the the new button as 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 this:
function addNewButton() {
$("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />");
}
$("#sweetness").live("click", function() {
$(this).remove();
});
I'm sorry to post to such an old and answered question. I had a similar problem and this answer helped me but didn't get me quite there. After trial and error... Here's my practical solution for adding areas to web page and removing them. I use it with dynamic form fields but your needs may vary.
Here's part of the form in the static portion 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 functions. These ones 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's 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's previous sibling
$('.dynExtra-clear').click(function(){
$(this).prev().remove();
$(this).remove();
});
}
</script>
Hopefully this helps someone and I didn't forget anything.