如果提交表单时两个div具有相同的值,如何返回false

时间:2018-05-03 19:59:59

标签: javascript jquery html

我有一个表单在div中有很多选择所以我想当用户提交表单如果有两个div或更多有 相同的值,形式示例第一个具有此值:1个,第3个具有 相同的值,所以不提交并返回false,那么有什么方法javascript或jquery可以帮助我做到这一点?



$("form").submit(function() {
   alert("2 div or more have the same value, please change them");
   return false;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div>
      <select class="number">
          <option value="">select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
     </select>
     <select class="letter">
          <option value="">select</option>
          <option value="one">one</option>
          <option value="two">two</option>
          <option value="three">three</option>
     </select>
 </div>
  <div>
      <select class="number">
          <option value="">select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
     </select>
     <select class="letter">
          <option value="">select</option>
          <option value="one">one</option>
          <option value="two">two</option>
          <option value="three">three</option>
     </select>
  </div>

  <div>
     <select class="number">
          <option value="">select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
     </select>
     <select class="letter">
          <option value="">select</option>
          <option value="one">one</option>
          <option value="two">two</option>
          <option value="three">three</option>
     </select>
  </div>
  <input type="submit"/>
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此javascript代码保留您的HTML

$("form").submit(function(event)
{
   var selects = $('select');
   selects.each(function(i,select1){        
   var found = false;
      selects.each(function(j,select2){         
           if(i!=j && select1.value == select2.value){
               alert("2 div or more have the same value, please change them");
               found = true;
               event.preventDefault();
               return false;
           }
       });
       if(found){
           return false;
       }
   });
});