jQuery add a link to remove a control dynamically
I can generate the controls but can't remove them. I'm trying to add a 'Link' which will call a function to remove dynamically created control. The control and link are next to each other. Here's the Java script and mark-up to create the control:
<script type="text/javascript">
$(function() { // when document has loaded
// <input id="File1" type="file" runat="server" size="60" />
var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work
$('a#add').click(function() { // when you click the add link
$('<p><input type="file" id="' + i + '" name="' +开发者_如何学Python 'dynamic:' + i + '" /> <a href="#" id="' + 're' + i + ' " onclick="removeControl("' + '\'#' + i + '\''+ '")">+</a></p>').appendTo('body'); // append (add) a new input to the document.
// if you have the input inside a form, change body to form in the appendTo
i++; //after the click i will be i = 3 if you click again i will be i = 4s
});
function removeControl(controlId) {
$(controlId).remove();
}
}); </script>
<div>
<a href="#" id="add">Add</a>
<br />
<p><input type="file" id="1" /></p>
</div>
The script to create the Link to remove the control is not working. The onClick attribute is not mark-up correctly when I use Firebug to see the source.
<a href="#" id="' + 're' + i + ' " onclick="removeControl("' + '\'#' + i + '\''+ '")">+</a>
I just wanna add a Link to remove the generated control and the link itself.
Thank you.
If you want to remove an element from the Dom which was included via javascript you need to attach or rebind an event handler.
$('a.remove').live('click', function() {
// Stuff to remove
});
Working solution:
<script type="text/javascript">
$(function() {
// Init counter
var counter = 0;
// Add Elements
$('#add').click(function() {
counter++ // Increment counter
var add_input = '<p><input type="file" />';
var add_link = '<a href="#" class="remove">Remove</a>';
// Append Elements if counter smaller 4
if (counter <= 4) {
$('body').append('<p>' + add_input + add_link + '</p>');
}
return counter;
});
// Remove Elements
$('.remove').live('click', function() {
counter--; // Decrement counter
$(this).parent('p').remove();
});
});
</script>
<a href="#" id="add">Add</a>
FYI-> Always reduce dom inserts to a minimum.
Try changing your removeControl function to this:
function removeControl(driver) {
$(driver).closest("p").remove();
}
Then, change the call to the function in your anchor to this:
onclick="removeControl(this);return false;"
Should be good to go...
精彩评论