gpt4 book ai didi

javascript - 检查表单中的任何复选框是否被选中(MooTools)

转载 作者:行者123 更新时间:2023-12-03 10:51:37 25 4
gpt4 key购买 nike

我正在使用带有各种复选框组的表单,并且我希望仅在选中任何复选框时才显示页面底部的下一个按钮。

我在这里找到了一个使用 jQuery 的可行解决方案:

var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");

checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));
});

http://jsfiddle.net/BPhZe/1937/

我正在寻找一种使用 MooTools 执行此操作的方法,并且我更喜欢一种按钮状态不是“禁用”而是通过 CSS 隐藏的解决方案。

最佳答案

MooTools 具有 Element.checked 属性来查看指定元素是否设置为“已选中”。 MooTools 还允许您将“:checked”添加到选择器中,以仅获取匹配的选定元素。这意味着您可以执行以下操作来确定是否选中了任何复选框:

if ($$("input[type=checkbox]:checked").length > 0)

或者确定当前没有选中复选框:

if ($$("input[type=checkbox]:checked").length < 1)

鉴于您链接到的示例表单,这是一种方法:

$$("input[type=checkbox]").each(function(checkboxInput) {
checkboxInput.addEvent("click", function() {
// show submit button if at least 1 checkbox is checked
if (checkboxInput.checked) {
$$("input[type=submit]").each(function(submitButton) {
submitButton.removeProperty("disabled");
});
}
// hide submit button if no checkboxes are checked
if ($$("input[type=checkbox]:checked").length < 1) {
$$("input[type=submit]").each(function(submitButton) {
submitButton.set("disabled", "disabled");
});
}
});
});

如果您的提交按钮有一个 id 属性 - 例如 id="formSubmitButton"- 您可以以这种方式引用它并使用稍微更少的代码完成相同的事情,而不必使用 $$("input[type=submit ]").each(function(submitButton) { ... } :

$("formSubmitButton").removeProperty("disabled");

要从禁用/重新启用按钮更改为显示/隐藏按钮,您可以使用属性 style="display:none;"设置的按钮启动表单,然后调用submitButton.removeProperty("style") 当复选框被选中时,以及 SubmitButton.setStyle("display", "none") 当不再选中任何复选框时。该版本的完整代码示例,使用带有 ID 的提交按钮:

$$("input[type=checkbox]").each(function(checkboxInput) {
checkboxInput.addEvent("click", function() {
// show submit button if at least 1 checkbox is checked
if (checkboxInput.checked) {
$("formSubmitButton").removeProperty("style");
}
// hide submit button if no checkboxes are checked
if ($$("input[type=checkbox]:checked").length < 1) {
$("formSubmitButton").setStyle("display", "none");
}
});
});

关于javascript - 检查表单中的任何复选框是否被选中(MooTools),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com