【发布时间】:2018-05-23 10:21:35
【问题描述】:
一个真正简单的 javascript 函数,我被困住了......(已经用谷歌搜索了很多,但无法让它完全工作!)。
基本上,我有两个复选框。我的免责声明消失了(仅当两个框都被选中时。(请参阅下面的完整代码)。
如果只选中一个/无框,则仍应显示免责声明。并且表单提交按钮被禁用。
一切正常。如果选中一个框,我可以使免责声明消失并停用按钮。但似乎什么也没做,下面是我的 if/else 语句。
基本上,我的 if/else 语句中的“if”没有检查正确的逻辑。
我用谷歌搜索并尝试了很多变化。但不能让这个工作。
谢谢!
var formInput = document.querySelector("input[name=terms]");
var marketingInput = document.querySelector("input[name=marketing]");
var cvSubmitButton = document.querySelector("input[type=submit]");
var checkBoxDiv = document.getElementById("checkboxRow");
var scfSubmitButtonBorder = document.querySelector(".scfSubmitButtonBorder");
cvSubmitButton.classList.add('disabled');
scfSubmitButtonBorder.style.cursor = "not-allowed";
var legalClause = document.createElement('div');
legalClause.innerHTML = "<div id='disclaimer'><br /><p>* Your applicaton cannot be submitted, unless you have agreed to read our Terms of Use, Privacy Policy and Cookie Policy.</p></div>";
checkBoxDiv.appendChild(legalClause);
// EVENTLISTENER
var boxes = document.querySelectorAll('input[type=checkbox]:checked').length;
formInput.addEventListener("change", function(){
if((formInput.checked) && (marketingInput.checked)) {
cvSubmitButton.classList.remove('disabled');
checkBoxDiv.removeChild(legalClause);
scfSubmitButtonBorder.style.cursor = "pointer";
console.log('checked');
} else {
cvSubmitButton.classList.add('disabled');
checkBoxDiv.appendChild(legalClause);
scfSubmitButtonBorder.style.cursor = "not-allowed";
console.log('not checked');
}
});
这是 HTML 片段:
<div id="checkboxRow" class="scfSectionContent">
<input type="checkbox" name="terms" value="terms"> * I have read and agree with the <a href="/terms-of-user" target="_blank">Terms of Use</a>, <a href="/privacy-policy" target="_blank">Privacy Policy</a> and <a href="/cookie-policy" target="_blank">Cookie Policy</a>.
<br>
<input type="checkbox" name="marketing" value="marketing"> I agree that Adecco Group AG can use my details to send me information about their activities. This may be by post, email, SMS, MMS, phone, social media, push notifications in apps and other means. I understand that I may opt out at any time.
<div><div id="disclaimer"><br><p>* Your applicaton cannot be submitted, unless you have agreed to read our Terms of Use, Privacy Policy and Cookie Policy.</p></div></div></div>
【问题讨论】:
-
if((formInput.checked) && (marketingInput.checked)), 正在检查两个条件是否为真,使用'||',这将触发任何一个没有被检查
-
当您仅在一个复选框 (
formInput) 上侦听更改事件时,您的代码将仅在该复选框更改时运行(当另一个 (marketingInput) 为改变)。也许监听两个复选框的变化可能会有所帮助?另外,请张贴Minimum Complete and Verifiable Example 说明问题以排除猜测:) -
您似乎只是将更改事件侦听器绑定到
formInput,而不是同时绑定到formInput和marketingInput。我假设您想在单击 either 复选框时运行逻辑?如果是这样,您需要绑定到两个复选框。 -
你能添加一些你的html,这样我们就可以有一个工作的sn-p了吗?
-
嗨,我刚刚添加了 html。我在 UAT 环境中工作,它似乎不喜欢 ES6,所以仅供参考:)
标签: javascript forms if-statement checkbox