[英]Disable button until AJAX generated radio buttons have been selected
I have a static submit button on my web page. 我的网页上有一个静态的提交按钮。
I make an AJAX call which generates a list of radio buttons. 我进行AJAX调用,生成一个单选按钮列表。 The number of radio buttons is random, all depends on the number of items in a JSON object. 单选按钮的数量是随机的,全部取决于JSON对象中项目的数量。
I am wanting to validate that all of the generated radio buttons have been selected before making the submit button available. 我想验证所有生成的单选按钮都已选中,然后再使提交按钮可用。
Currently my HTML looks like this: 目前,我的HTML如下所示:
<div id="toDo" class="col-sm-6 text-center">
<div id="manualChecks" class="panel panel-default">
<div class="panel-heading text-center"><strong>Manual Check</strong</div>
</div>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">Submit</button>
</span>
</div>
My ajax reads a .JSON file and generates a list of checkboxes via the following javascript: 我的ajax读取.JSON文件,并通过以下JavaScript生成复选框列表:
var ul = $('<ul class ="list-group text-left">');
$.each(item, function (key, value) {
var li = $('<li class="list-group-item">').append(
$('<input type="radio">' + value.Description + '</input>')
);
li.appendTo(ul);
});
$('#manualChecks').append(ul);
}
All of this works like a charm. 所有这些都像魅力一样。 I am just wanting to "validate" this dynamicaly generated form. 我只是想“验证”这种动态生成的表格。 I do not want to be able to press the Submit
button until all of the auto generated radio buttons have been selected. 在选择了所有自动生成的单选按钮之前,我不希望能够按下“ Submit
按钮。
Begin with your button disabled 从禁用按钮开始
<button id="submitBtn" disabled="disabled" type="submit" class="btn btn-primary">Submit</button>
then when you're done checking that all the buttons are selected, remove the disabled attribute. 然后,当您检查完所有按钮都被选中后,请删除Disabled属性。
$('#submitBtn').removeAttr('disabled');
To check all the buttons are selected you'd need to write some logic for that. 要检查所有按钮是否都被选中,您需要为此编写一些逻辑。 Just add a handler on the radio buttons to listen for when they are changed and then select them all and see if the number that are unchecked === 0. 只需在单选按钮上添加一个处理程序即可侦听它们的更改情况,然后将其全部选中,然后查看是否未选中的数字=== 0。
Disable button before AJAX request starts. 在AJAX请求开始之前禁用按钮。
delegate an event to the form to check for change events on radio buttons within the list. 将事件委托给表单,以检查列表中单选按钮上的更改事件。
var $submit = $('#submitBtn');
var $todo = $('#toDo');
$todo.on('change', 'input[type="radio"]', function (e) {
var unCheckedInputs = $todo.find('input[type="radio"]:not(:checked)');
if (unCheckedInputs.length === 0) {
$submit.prop('disabled', false);
}
});
Side note your inputs are malformed. 旁注,您的输入格式不正确。 you are generating code that looks like this 您正在生成看起来像这样的代码
<input type="radio">Some Label</input>
What you want to be making is something like 你想做的是像
<label>
Some Label
<input type="radio" value="" />
</label>
Inputs are self closing tags and normally do not wrap text values. 输入是自闭标签,通常不包装文本值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.