Reputation: 15
I have created a dropdown menu in html. I have a reset button which resets all the value to null. But on clicking this I need to reset the dropdown menu to the first value which I gave in the field.
Please help... The code for the dropdown is as below.
<select name="abc" id="abc">
<option value="one">One
<option value="two">Two
</select>
But on clicking Reset I am getting a blank in the dropdown list from where i have to again select either One or Two. Instead I want it to automatically set to the value "One".
Upvotes: 2
Views: 106
Reputation: 505
HTML select drop down by default shows first option if none of the option is selected. So, effectively you just need to clear the selected
attibute for your dropdown.
function clearForm(form) {
//var $f = $(form);
//var $f = $f.find(':input').not(':button, :submit, :reset, :hidden');
//$('#msg').empty();
$('#abc option:selected').removeAttr('selected');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="abc" id="abc">
<option value="one">One
<option value="two" selected>Two
</select>
<input type='button' class="btn btn-primary" value='Reset' name='reset' onclick="return clearForm(this.form);">
Upvotes: 0
Reputation: 545
I think you need this code in your reset jquery function.
$("#abc option:selected").prop("selected", false);
$("#abc option:first").prop("selected", "selected");
Upvotes: 0
Reputation: 76547
You just need to use the selected
attribute for the item that you want to be the default:
<select name="abc" id="abc">
<option value="one" selected="selected">One</option>
<option value="two">Two</option>
</select>
If you are manually performing the reset, you'll likely want to store a reference to the current selection prior to resetting them and using that to retain the previous selection, which you can access via the selectedIndex
property. Depending on your use case and technology (e.g. jQuery, etc.), you can select a specific element by its index, value, or potentially other attributes.
Upvotes: 1
Reputation: 5742
use selected
here live example https://www.w3schools.com/tags/att_option_selected.asp
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
Upvotes: 0
Reputation: 5708
You can use add the attribute selected
to the option you want to be default like this:
<select name="abc" id="abc">
<option value="one">One</option>
<option value="two" selected>Two</option>
</select>
Or add selected="selected"
:
<select name="abc" id="abc">
<option value="one" selected="selected">One</option>
<option value="two">Two</option>
</select>
Upvotes: 1
Reputation: 3807
You can add selected
attributes to make default select.
<select name="abc" id="abc">
<option value="one">One
<option value="two" selected="selected">Two
</select>
With jquery
$("#abc").val("two")
Upvotes: 0