Javascript to select the first list selection option

I need to create a reset button, which, by clicking, will install all the selection lists in the form for index 0. I tried this code for the function, but it gives a syntax error on myForm.length;

<script type="text/javascript">function ResetForm(form) { var myForm = document.forms[form]; for( var i=0; i < myForm.length; i++ ){ myForm.select[i].selectedIndex =0; } } </script> 
+8
source share
7 answers

There is no property like someForm.select , try this instead:

 selectTags = myForm.getElementsByTagName("select"); for(var i = 0; i < selectTags.length; i++) { selectTags[i].selectedIndex =0; } 
+19
source

You just need to set the .selectedIndex property, as in mySelect.selectedIndex = 0; . Try the example below.

 var doc = document; var myCheckbox = doc.getElementById('my-checkbox'); var mySelect = doc.getElementById('my-select'); myCheckbox.addEventListener("click", function(e){ if (this.checked){ mySelect.disabled = false; } else { mySelect.selectedIndex = 0; mySelect.disabled = true; } }); 
 <label><input type="checkbox" id="my-checkbox" value=""> Enable Dropdown</label><br> <select id="my-select" disabled> <option class="placeholder" selected disabled value="">Select credential</option> <option value="apples">apples</option> <option value="oranges">oranges</option> <option value="bananas">bananas</option> </select> 
+3
source

Here you can find jquery. This SHOULD do the trick ...

 $(function() { $('.resetButton').click(function() { $(this).closest('form').find('select').each(function() { $(this)[0].selectedIndex=0; }); }); }); 

<input type="reset" class="resetButton" />

0
source

This will be every choice immediately after the transition to the first option:

  <select onchange="your_selection_func(); this.selectedIndex=0;"> 
0
source

I found a hack:

 <select onchange="doSomething()"> <option value="a" selected disabled hidden>a</option> <option value="a">a</option> <option value="b">b</option> <option value="…"></option> </select> 

the combination of selected disabled hidden causes the first option (visualy) to respond with a change event (even with the same value !).

Work with IE, Edge, Opera, Chrome, but does not work in FF :(

0
source

A small note for a response from Ron Royston (I tried this only on Chrome 74.0)

Setting mySelect.selectedIndex = 0; or $('#mySelect').prop("selectedIndex", 0); will not work if the option is disabled.

Hope this saves someone time and frustration!

0
source

I understand that this is kind of old, but I would like to improve the answer to one. There is no reason to create a jQuery object from 'this' when you are just going to extract a DOM element from it:

 $(this).closest('form').find('select').each(function() { this.selectedIndex = 0; }); 
-1
source

Source: https://habr.com/ru/post/909850/


All Articles