0

In my understanding, a select value will set default value in 2 ways:

  1. Check if "selected" attribute for any option
  2. 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

Hemant Halwai
  • 396
  • 2
  • 8
  • 1
    Have a look at this maybe, it will help https://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-element – Alex Susanu Jun 16 '21 at 19:10
  • The presence of `[default]` attribute on an `` the value in this case is `"Select Gender"`. – zer00ne Jun 16 '21 at 19:17

2 Answers2

1

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.

Moshe Sommers
  • 1,466
  • 7
  • 11
1

Here's another way. Use css selectors to get the count of all option elements that are selected (and have a value). If the count is zero, choose the index of the one you want (in this example #2)

let sel = document.querySelector('select[name="gender"]');
if (sel.querySelectorAll('option:checked[value]').length === 0) {
  sel.querySelectorAll('option')[1].setAttribute('selected', 'selected');
}
<select name="gender">
  <option>Select Gender</option>
  <option value="1">Male</option>
  <option value="2">Female</option>
  <option value="3">Other</option>
</select>
Kinglish
  • 23,358
  • 3
  • 22
  • 43