javascript - 检查具有相同值的输入?

标签 javascript jquery html forms

我想检查输入是否具有相同的值

输入是由循环生成的,每次数字都会不同

for(int i = 0; i< add; i++) 
{%>
<input  name="<%= i%>" id="<%= i%>" class="form-control" holder="S/Num"/>
<%} %>

我尝试过这个,但没有成功

<script>
$('input').blur(function() {
  if ($('#s1').attr('value') == $('#s2').attr('value')) {
    alert('Same Value'); return false;
  } else { return true; }
});
</script>

最佳答案

试试这个:

$(function() {
  var nums = $('input.form-control[id^=s]'); /* find all inputs starting id with `s` */
  nums.on('change', function(e) {
    var map = {};
    nums.each(function(i, el) {
      if (el.value.replace(/\s/g, '')) { /* trim whitespace */
        if (undefined !== map[el.value]) {
          console.log('duplicate value', el.value, ', found input with id', el.id);
          el.value = ''; /* reset, if required */
        } else {
          map[el.value] = 1;
        }
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="s1" id="s1" class="form-control" placeholder="S/Num" />
<input name="s2" id="s2" class="form-control" placeholder="S/Num" />
<input name="s3" id="s3" class="form-control" placeholder="S/Num" />

关于javascript - 检查具有相同值的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574694/

相关文章:

javascript - 在库中包含 <div></div>

javascript - 使用 Angular 动态生成的选择选项未选择默认值

javascript - 如何让div float 在滚动条上?

javascript - 从用户输入边计算三 Angular 形面积和周长

javascript - 等待 Node js中的事件

javascript - 带类(class)的 child

javascript - 在服务器-客户端往返期间存储(或传递)Element/TableCell 引用

javascript - 使用 jQuery 解析外部 JSON 文件

javascript - Jquery 只选择 div 中的第一个 ul

html - Bootstrap 导航栏不会在 iPhone 上折叠