What would be the best way to reset the selected item to default? I'm using Select2 library and when using a normal button type="reset"
, the value in the dropdown doesn't reset.
So when I press my button I want "All" to be shown again.
jQuery
$("#d").select2();
html
<select id="d" name="d"> <option selected disabled>All</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select>
In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();
To set selected value of jQuery Select2 with JavaScript, we call val and then trigger . Then we set its value with val to the option with value 0. Finally, we call trigger with 'change' to update the drop down to show the value we set.
If you want to reset the whole form, just call the built-in JavaScript . reset() on the <form> element. Also <select> has a defaultSelected which could be used in the function to reset if you just want a single element reset - see stackoverflow.com/questions/2348042/…
I'd try something like this:
$(function(){ $("#searchclear").click(function(){ $("#d").select2('val', 'All'); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With