javascript检查输入值是否重复?

时间:2017-08-29 08:04:13

标签: javascript

如何检查输入的文本值是否重复?

<%for(int i =0;i<5;i++){%>
<input type="text" id="time<%=i%>" onblur="fnValidate(<%=i%>,this.value)">
<%}%>

的JavaScript

我尝试了类似下面的示例,但逻辑是错误的。

&#13;
&#13;
function fnValidate(count,value)
    {

      for(var i =0; i<5 ; i++)
      {
           if(i !== count && document.getElementById("time"+i).value == value)
             document.getElementById("time"+count).style.background ="#ff0000";
             else 
             document.getElementById("time"+count).style.background ="#fff";

      }

    }
&#13;
<input id="time0" onchange="fnValidate(0, this.value)">
<input id="time1" onchange="fnValidate(1, this.value)">
<input id="time2" onchange="fnValidate(2, this.value)">
<input id="time3" onchange="fnValidate(3, this.value)">
<input id="time4" onchange="fnValidate(4, this.value)">
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您需要检查i !== count是否跳过当前字段。

function fnValidate(current, value){
  var hasDuplicates = false

  for(var i =0; i<5 ; i++) {
   if(i !== current && document.getElementById("time"+i).value == value) {
    hasDuplicates = true
    break
   }
  }

  document.getElementById('time' + current).style.backgroundColor = hasDuplicates ? '#F00' : '#FFF'
}
<input id="time0" onchange="fnValidate(0, this.value)">
<input id="time1" onchange="fnValidate(1, this.value)">
<input id="time2" onchange="fnValidate(2, this.value)">
<input id="time3" onchange="fnValidate(3, this.value)">
<input id="time4" onchange="fnValidate(4, this.value)">