Chrome html在select元素上形成了错误的验证

时间:2014-06-12 09:45:27

标签: javascript forms validation google-chrome html-select

Chrome似乎没有以我期望的方式验证<select>。 如果我选择第一个选项,而Chrome选择第二个选项,则Firefox会正确返回false。在Windows和Linux上都会发生这种情况。

我的HTML

<form>
<select name="select-choice" id="select-choice" required>
  <option value="">This is just a placeholder, it should invalidate the form</option>
  <option value="choice2">Choice 2</option>
  <option value="choice3">Choice 3</option>
</select>
</form>

我的JS

$('form').change(function(){
   $('.result').html('form is ' + this.checkValidity());
});

CodePen

Here is a code pen

1 个答案:

答案 0 :(得分:1)

这看起来像是一个jQuery错误。如果是这样,这里有一个功能性的vanilla / native Javascript:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <form id="theForm">
        <select name="selectChoice" id="selectChoice" required>
            <option value="">Invalidating placeholder</option>
            <option value="choice2">Choice 2</option>
            <option value="choice3">Choice 3</option>
        </select>
    </form>
    <script>
        var selectChoice = theForm.selectChoice;
        selectChoice.onchange = function() {
            if (selectChoice.value == '') alert('Invalid selection.');
            else alert('Valid selection.');
        }
    </script>
</body>
</html>

实例也是一个codepen:http://codepen.io/anon/pen/hqutj?editors=100

或者在jQuery中,您可能想尝试不使用函数checkValidity(),这似乎返回options.selectedIndex,但要检查select的空值。

编辑:旁注:required似乎是任何浏览器都不支持的属性,至少在本机Javascript中不支持。见http://www.w3schools.com/tags/att_select_required.asp

相关问题