Home > Enterprise >  how to get event listener not to ignore if the first element in the select menu is clicked
how to get event listener not to ignore if the first element in the select menu is clicked

Time:05-16

i have tried the traditional method of addEventListener change but if i click on the first element on the list it wont respond, it only works if i click on australia then india...

HTML

<select id="country" >
 <option value="india">India</option>
 <option value="australia">Australia</option>
 <option value="turkey">Turkey</option>
</select> 

JS

var a = document.getElementById('country');
a.addEventListener('change', function() {
  alert(this.value);
}, false);```

CodePudding user response:

Its working as expected, as per 'change event' works when HTMLElement changes its value. With your 'select' element, it will not change its value when you select the same value is already selected.

You can add a default 'Select your value...' or something else you want, to prevent this behavior and accomplish what you are looking for.

HTMLElement: change event

var a = document.getElementById('country');
a.addEventListener('change', function() {
    if (this.value === 'default')
        return;
    alert(this.value);
}, false);
<select id="country" >
   <option value="default">Select country</option>
   <option value="india">India</option>
   <option value="australia">Australia</option>
   <option value="turkey">Turkey</option>
</select>

CodePudding user response:

You can add a default <option> like the the following:

<option selected disabled>DEFAULT</option>

Or you can use a more direct event like "click"

document.querySelector('#country').addEventListener('click', function(e) {
 document.querySelector('#view').value = this.value;
});
<output id='view'></output><br>
<select id="country" >
 <option value="india">India</option>
 <option value="australia">Australia</option>
 <option value="turkey">Turkey</option>
</select> 

  • Related