2014-06-12 15 views
0

看來Chrome並沒有按照我的預期驗證<select>。 如果我選擇第一個選項,而Chrome會選擇第二個選項,Firefox將正確返回false。這在Windows和Linux上都會發生。Chrome html表格在select元素上的錯誤驗證

我的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

這看起來像一個jQuery的bug。如果是這樣,這裏是一個功能的香草/原生的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

+0

This Works。還有一點讓我感到奇怪的是'checkValidity()'不是jQuery,也是原生JavaScript,[必須應該工作](http://caniuse.com/#search=required)。如果沒有更好的東西出來,我會接受這個答案。 – stilllife

+0

@MirkoGuarnier - 可愛,那'checkValidity()'。從來沒有聽說過它,但它會使編碼變得更容易。然而,在這個時候,由於錯誤的瀏覽器支持或者沒有瀏覽器支持,它在結構上似乎是錯誤的。請參閱http://sanalksankar.blogspot.nl/2010/12/form-validation-using-checkvalidity-and.html,這是前面的段落。關於'required':有了這麼差的瀏覽器支持(沒有IE8/9,也沒有iOS Safari),我現在會忘掉它。太忙了。 –