2017-06-15 86 views
0

如何驗證多個組中的兩個單選按鈕,其中一個單選按鈕爲true,另一個爲false。我正在使用JavaScript,但無法正常工作。我的意思是,如果我從這些組中選擇任何一臺收音機,它將進行驗證並提交。請參閱下面的代碼。驗證多個組的兩個單選按鈕

<form name="form1" action="http://example.com/" onsubmit="return 
    validateForm()" method="post"> 
    <div class="btn-group" data-toggle="buttons"> 
     <label id="yes" class="btn btn-success"> 
     <input id="true" name="options" type="radio" /> Yes 
     </label> 
     <label id="no" class="btn btn-success"> 
     <input id="false" name="options" required="" type="radio" /> No 
     </label> 
    </div> 
    <div class="btn-group" data-toggle="buttons"> 
     <label id="yes1" class="btn btn-success"> 
     <input id="true" name="options" type="radio" /> Yes 
     </label> 
     <label id="no1" class="btn btn-success"> 
     <input id="false" name="options" required="" type="radio" /> No 
     </label> 
    </div> 
    </form> 
    <script> 
    function validateForm() { 
    var radios = document.getElementsById("true"); 
    if (radios.checked = true) { 
     return true; 
    } else { 
     alert("error"); 
    } 
    } 
    </script> 

我想驗證所有的真實選項。如果其中任何一個被錯誤選中,它應該會給出錯誤。你能幫我麼?

+0

**你好!**你不能在頁面上有幾個相同的** ID **。有必要重寫HTML。 –

回答

0

給你,

香草JavaScript解決方案:

<form id="form_1" name="form" action="#" method="POST"> 
 
    <div class="btn-group" data-toggle="buttons"> 
 
    <input class="radio_btn" type="radio" name="group1" value="true">Yes 
 
    <input class="radio_btn" type="radio" name="group1" value="false">No 
 
    </div> 
 
    <div class="btn-group" data-toggle="buttons"> 
 
    <input class="radio_btn" type="radio" name="group2" value="true">Yes 
 
    <input class="radio_btn" type="radio" name="group2" value="false">No 
 
    </div> 
 
    <button type="submit">Submit</button> 
 
</form> 
 

 
<script> 
 
    var form = document.querySelector('#form_1'); 
 
    var radioList = form.querySelectorAll('.radio_btn'); 
 

 
    form.addEventListener('submit', function() { 
 
    for (var i = 0, length1 = radioList.length; i < length1; i++) { 
 
     if (radioList[i].getAttribute('value') == 'false' && radioList[i].checked) { 
 
     alert("error"); 
 
     return false; 
 
     } 
 
    } 
 
    }); 
 
</script>

*我重寫的HTML代碼。

+0

所有工作正常,但我想重定向它,如果真實的一個被選中....我試圖與行動=「#」但問題它會重定向天氣其真或假 –