Reputation: 181
I have a search form with some dropdowns which the user can leave empty. Now I want to remove these select elements before the form is submitted.
I tried this, but with this function all my select dropdowns are removed:
$('select option[value=""]').parent().remove();
Thanks for your help cheers dan
Upvotes: 2
Views: 1737
Reputation: 11337
Assume that if the first option in selected - means that the dropdown wasn't selected, I suggest:
$("option:first-child:selected")
to select all first 'option' tags which are selected (by default, if none of the other options were selected. Than you can choose their parent and remove as you did before.
Hope that's help
Upvotes: 0
Reputation: 3419
You should change your view. When you create a select use an "empty" option like:
<form class="form">
<select id="select1">
<option value="-1"> - </option>
....
</select>
<select id="select2">
<option value="-1"> - </option>
....
</select>
</form>
Then when the form is submitted remove all the selects. I don't understand why you have to remove them... Are you making an Ajax call to submit the form?
$(document).ready(function() {
$('.form').submit(function(e) {
var selects = $(this).find('select');
$.each(selects, function(idx, value) {
if($(this).val() === -1) {
$('.form').find($(this).attr('id')).remove();
}
})
});
});
Upvotes: 0
Reputation: 32980
I assume your selects all have an option with value ""
which is used as empty option.
Then your jquery call effectively removes all these selects.
When you want to select and remove the select elements where the user did not set another option you can write:
var s = jQuery("select").filter(function() {
return !this.value;
}).remove();
Upvotes: 1