In my understanding, a select value will set default value in 2 ways:
- Check if “selected” attribute for any option
- Else place first option as selected
<select name="gender"> <option>Select Gender</option> <option value="1">Male</option> <option value="2">Female</option> <option value="3">Other</option> </select>
Is there any way through which I can find out by which step(above mentioned) is the default value set for this select
Advertisement
Answer
You can loop through the options and check if there’s a selected attribute.
const options = Array.from(document.querySelector('[name=gender]').children); //If there isn't a selected attribute it will be undefined options.forEach(c => { console.log(c,!!c.attributes.selected); })
Note: Selecting from dropdown doesn’t add the selected attribute so this code will be true even after user chooses an option.