我想禁用提交按钮,直到选中一组单选按钮。我知道有类似的问题,但没有一个属于动态创建的单选按钮组......
以下是我的内容..页面顶部的脚本会在上一个视图中生成一些用户上传的按钮:
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" />
非常感谢!
答案 0 :(得分:1)
事件委托(同样,在将.prop()
属性移除到提交按钮时使用disabled
$("#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);
}
});
答案 1 :(得分:1)
我明白了。正如Benjamin在上面的评论中所建议的,后一个脚本在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");
}
});
});