kshep92
kshep92

Reputation: 895

HTML Select reports wrong validity on change event in IE 11

I'm trying to add a change event handler to a select tag, but for some reason IE reports the wrong validity - it's always valid no matter what. see plunk

What's weird is if I manually inspect the select tag afterward in the console and type $0.validity.valid it reports the right value.

Here's the code:

    <select name="choices" id="sel" required>
        <option value="">Nothing</option>
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
    </select>
    <span id="output"></span>
    <script>
        document.addEventListener('DOMContentLoaded', function() { 
            document.getElementById('sel').addEventListener('change', function(event) {
                document.getElementById('output').innerHTML = 'Field value: ' + event.target.value + '; Valid: ' + event.target.validity.valid; 
            });
        });
    </script>

Is this a bug in IE or with my code?

Everything works fine in Chrome btw.

Upvotes: 0

Views: 866

Answers (1)

Tommie
Tommie

Reputation: 783

This is a browser quirk and thus you need to check the actual string. A tip is to always do that and not rely on the browser setting "empty" strings as false/true since you'll keep running into these small quirks if you do.

Here's an example of how one could do it:

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('sel').addEventListener('change', function(event) {
    var current = event.target.value;
    if( current == ''){ event.target.value = false; }
    document.getElementById('output').innerHTML = 'Field value: ' + current + '; Valid: ' + event.target.validity.valid; 
  });
});
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <select name="choices" id="sel" required>
        <option value="">Nothing</option>
        <option value="1">1</option>
        <option value="2" selected>2</option>
        <option value="3">3</option>
    </select>
    <span id="output"></span>
  </body>

</html>

Upvotes: 1

Related Questions