2017-08-08 182 views
0

我有一些代碼檢查是否至少選中了一個複選框,然後提交表單(MailChimp)。我的問題是我不知道如何阻止MailChimp提交,如果它發現沒有選中複選框。現在它顯示警報,然後提交表單......無論如何......沒有什麼幫助。使用所需的複選框驗證來阻止表單提交

<form onsubmit="valthis()" action="//mailchimp form" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate> 

// form html 

     <script>function valthis() { 
var checkBoxes = document.getElementsByClassName('myCheckBox'); 
var isChecked = false; 
    for (var i = 0; i < checkBoxes.length; i++) { 
     if (checkBoxes[i].checked) { 
      isChecked = true; 
     }; 
    }; 
    if (isChecked) { 
     alert('At least one checkbox is NOT checked!'); 
     } 
}</script> 

<input type="submit" value="Subscribe to notifications" name="subscribe" id="mc-embedded-subscribe" class="button"> 

回答

0

處理數據時你可以做return你的JS函數的值:

<form onsubmit="return valthis()" action="//mailchimp form" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate> 

<script> 
function valthis() { 
    var checkBoxes = document.getElementsByClassName('myCheckBox'); 
    var isChecked = false; 

    for (var i = 0; i < checkBoxes.length; i++) { 
     if (checkBoxes[i].checked) { 
      isChecked = true; 
      break; //don't need to continue the loop once a checkbox was found 
     } 
    } 

    if (!isChecked) { 
     alert('At least one checkbox is NOT checked!'); 
     return false; 
    } 

    return true; 
} 
</script> 

<input type="submit" value="Subscribe to notifications" name="subscribe" id="mc-embedded-subscribe" class="button"> 
1

您需要添加事件對錶單提交

document.getElementsByName("subscribe").onsubmit(function(event) { 
    if(!isChecked) { //If not checked 
     event.preventDefault(); // stops the form submitting 
    } 
}); 

如果沒有複選框的是檢查preventDefault。這停止提交表格

+0

我在當前javascript下添加了'document.getElementsByName'代碼。不行。我把它放在錯誤的地方? (){ – testing123

+0

'function valthis(){ var checkBoxes = document.getElementsByClassName('myCheckBox'); var isChecked = true;對於(var i = 0; i testing123

+0

像@ user5753132表示你需要將它添加到函數之外 – y0hami