How to delete the whole li element containing selectbox using Jquery?
I am trying to delete my dynamic selectbox if user choose to click on Delete (next to the selectbox). But I can't figure out how to impose the delete.
This is my code so far:
$(function() {
// set the array
var fruit = new Array("Apple", "Orange", "Pear", "Banana");
var id = 0;
function addFruit() {
$.each(fruit, function(key, value) {
$('#fruit')
.append($('<option>', { value : key })
.text(value));
});
}
var i = $("li").size() + 1;
$("a#addmore").click(function() {
$("#addmore_row").append('<li>' +
'<select name="fruit开发者_运维问答[]" id="fruit_'+ id +'">' +
'<option value="">Select Fruit:</option>' +
'</select>' + '<a href="#" id="del_'+id+'">Delete Row</a>' +
'</li>');
addFruit();
id++;
return false;
});
});
Correct me if I am wrong, I think it's something like this. But I can't figure out what to put for [item]. Can please advise?
$([item]).click(function() {
$([item]).remove();
return false;
});
Thank you very much.
Sincle li has no id you can use traversing:
$('#del_'+id).click(function(event){ $(this).parent().remove(); event.preventDefault(); })
or add class to the remove link and just use:
$('.buttonToRemoveRowClass').click(function(event){ $(this).parent().remove(); event.preventDefault() })
may not answer your question but by guessing your markup as
<li>
<select>
<option>as
</option>
</select>
<a href="#">Delete Row</a>
</li>
you can try
$("a[href='#']:contains('Delete Row')").click(function(){
$(this).prev('select').remove();
$(this).fadeOut('slow');
});
have look here http://jsfiddle.net/nsJF5/
you can have a look here to see how prev
works.
If you have a reference to an element, you can remove it from the DOM using:
element.parentNode.removeChild(element);
There's likely a shorter jQuery version if you want less typing.
The parent element of the link is the li, so remove the parent when you click the link:
$("#addmore_row").append('<li>' +
'<select name="fruit[]" id="fruit">' +
'<option value="">Select Fruit:</option>' +
'</select>' + '<a href="#" id="del_'+id+'"' +
'onclick="$(this).parent().remove(); return false;">Delete Row</a>' +
'</li>');
If your delete link is contained in the same dom element (i.e. a div
) of the select you can traverse the dom by going up to this parent div an then finding the select
to remove inside it. Sort of:
$("a.delete").click(function(){
$(this).parents("div").find("select#fruit").remove();
});
If the delete link is a DOM successor of the select you can use .prev()
:
$("a.delete").click(function(){
$(this).prev("select#fruit").remove();
});
精彩评论