Reputation: 8225
I have a select box, from which I want to remove selected choice with jquery. Please advise me how I can make this working: this is the code for the markup:
@foreach (var item in Model.Names)
{
<div>
<div class="editor-field">
<select multiple id="@("Select" +item.Name)" name="@("Select" +item.Name)"></select>
</div>
<div>
<a href="#" id="remove">Remove selection</a>
</div>
</div>
}
There are three select boxes and for each one I need to add a hyperlink for removing selection. Thanks in advance, Laziale
Upvotes: 3
Views: 1558
Reputation: 11615
@foreach (var item in Model.Names)
{
<div class="listContainer">
<div class="editor-field">
<select multiple id="@("Select" +item.Name)" name="@("Select" +item.Name)"></select>
</div>
<div>
<a href="#" class="remove">Remove selection</a>
</div>
</div>
}
$('.remove').click(function(){
$(this).closest('.listContainer').find('select').find(':selected').remove();
});
Upvotes: 1
Reputation: 2644
Do you want to remove the selection or the selected elements?
As the removal of the elements has been answered, in the case it's just the selection:
$('.remove').click(function(){
$(this).closest('select').children().is(':selected').prop("selected",null);
});
EDIT:
$('.remove').click(function(){
$(this).parent().prev().find('option:selected').prop("selected",null);
});
Upvotes: 1
Reputation: 76003
First off you should change id="remove"
to class="remove"
since you will have multiple of these elements and it's not valid HTML to have the same ID used multiple times.
You can use jQuery to select the anchor tags and bind an event handler that removes the anchor's parent element (which also contains the <select>
elements):
$(function () {
$('.remove').on('click', function () {
$(this).parent().parent().remove();
return false;
});
});
Here is a demo: http://jsfiddle.net/7SueN/2/
Note that .on()
is new in jQuery 1.7 and in this case is the same as using .bind()
: http://api.jquery.com/on
If you want to only remove the <select>
element associated with each link you can target it for removal:
$(function () {
$('.remove').on('click', function () {
$(this).parent().parent().find('select').remove();
return false;
});
});
Here is a demo: http://jsfiddle.net/7SueN/1/
I just re-read your question and if you want to remove the selected index of the select when the link is pressed:
$(function () {
$('.remove').on('click', function () {
var $select = $(this).parent().parent().find('select');
$select.children().filter(':selected').remove();
return false;
});
});
Here is a demo: http://jsfiddle.net/7SueN/
Upvotes: 1