Delete a selected form element
I have a form element that needs to be deleted when a button next to the element is clicked.
$('#btnDel').click(function() {
var num = $('#input').prevAll().size();
$('#form div:nth-child('+ num +')').remove();
}
Can't seem to get that working! Any help very much appreciated. I think I'm just confused with selecting the right element...
EDIT: with markup as requested:
<div id="form">
开发者_开发知识库<form name="create" method="post" action="create.php">
<input type="hidden" id="id" value="1">
<label for="title">Title</label>
<input name="myusername" type="text" id="myusername"><br /><br />
<div id="input" class="clonedInput">
Question: <input type="text" name="question" id="question" />
<input type="button" id="btnDel" value="Remove question" />
</div>
<div>
<input type="button" id="btnAdd" value="Add another question" />
</div>
<input type="submit" name="submit" value="Create survey">
</form>
</div>
First, you'll need multiple delete buttons so give them a class, not an id class="btnDel"
then use this code:
$(".btnDel").click(function(){
$(this).closest("div").remove()
})
The #btnDel indicates that you are addressing a button with the id=btnDel. If that is the case there should only be one button because each id needs to be unique. If there is only one button there should only be one element next to it needing removal. Otherwise you can use the event portion of the click function to capture event.target and work relative to that to target removal.
$(".btnDel").click(function(e){$(this).parent().remove()});
I addressed this problem in your other question about deleting an element and changing the count. What you need is a single "Add Question" button and a "Delete Question" button for each question. Then each question and "Delete Question" button needs to have a class assigned to it and not an ID!
You can use the code I posted (and working example) in the other question, but essentially you need to use live query on the delete button since it is added dynamically.
HTML
<div id="input" class="clonedInput">
Question: <input type="text" name="question" class="question" />
<input type="button" class="btnDel" value="Remove question" />
</div>
Script
$('.btnDel').live('click',function(){
$(this).parent().remove();
})
精彩评论