[英]Disable submit button until one in a group of dynamically-created radio buttons selected
我想禁用提交按钮,直到选择了一组单选按钮之一。 我知道那里也有类似的问题,但都与动态创建的单选按钮组无关。
这就是我所拥有的..页面顶部的脚本为用户在上一个视图中上传提供了许多按钮:
var jScriptArray = new Array(@ViewBag.ColNames.Length);
var array = @Html.Raw(Json.Encode(ViewBag.ColNames));
for( var i = 0; i < @ViewBag.ColNames.Length; i++ ) {
jScriptArray[i] = array[i];
}
var length = @(ViewBag.NCols);
$(document).ready(function () {
for (var i = 0; i < length; i++) {
$('#radioGroupBy').append('<input id="grp' + i +'" type="radio" name="group" value="'+i+'">'+jScriptArray[i]+'</input>')
$('#radioGroupBy').append('<p style="padding:0px;margin:0px;"></br></p>');
}
});
这有效,选择任何按钮都将返回正确的值; 大。 但是,我想禁用提交按钮,直到选择了这些单选按钮之一。 使用我之前在SO上找到的答案,我创建了以下内容(此方法有效,但仅当我对按钮组进行硬编码时才起作用。问题是它不适用于Javascript创建的组):
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
另外,为了透彻,这里是提交按钮:
<input id="submitbtn" name="submitbtn" type="submit" value="Drill Down" disabled="disabled" />
非常感谢!
事件委托(此外,将disabled
属性删除到“提交”按钮时,请使用.prop()
)
$("#radioGroupBy").on("change", ":radio[name=group]", function() {
var $radioButtons = $(":radio[name=group]");
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
$("input[name='submitbtn']").prop("disabled", false);
}
});
我想到了。 正如本杰明在上述评论中所建议的那样,后一个脚本是在DOM准备就绪之前执行的。 我通过将整个脚本放在$(window).load ...中来解决它:
$(window).load(function () {
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.