简体   繁体   English

无法根据复选框启用/禁用提交按钮(JavaScript)

[英]Trouble enabling/disabling submit button according to checkbox (JavaScript)

I am trying to enable/disable my submit button based on whether or not the confirmation checkbox is checked. 我试图根据是否选中确认复选框来启用/禁用我的提交按钮。 The simplified version works just fine on jsfiddle but for some reason it doesn't work in my actual code. 简化版本在jsfiddle上正常工作,但是由于某种原因,它在我的实际代码中不起作用。 Here is the original code: 这是原始代码:

<div class="form-group">
    <div class="col-md-offset-3 col-md-6">
        <label>
            <input type="checkbox" id="confirm">The above information is correct.
        </label>
    </div>
</div>        
<div class="form-group" style="float:right">
    <input type="submit" class="btn btn-primary" id="sbmBtn" value="Submit" disabled>
    <input type="reset" class="btn btn-default" id="clrBtn" value="Clear">
</div>

I used the same method as I did in the functioning jsfiddle code (with the correct IDs of course), but it doesn't seem to work.. I even copy pasted my jsfiddle code into my editor, saved, and opened the page and it didn't work either. 我使用了与正常工作的jsfiddle代码相同的方法(当然具有正确的ID),但似乎无效。.我什至将粘贴的jsfiddle代码复制到编辑器中,保存并打开页面,它也不起作用。

Anyone have any ideas as to what the problem is? 任何人对这个问题有什么想法?

EDIT: Also here is the javascript: 编辑:这也是javascript:

var checker = document.getElementById('confirm');
var sbm = document.getElementById('sbmBtn');
checker.onchange = function () {
    if(this.checked) {
        sbm.disabled = false;
    } 
    else {
        sbm.disabled = true;
    }
}

EDIT 2: This is the correct link --> http://jsfiddle.net/94Dur/1/ 编辑2:这是正确的链接-> http://jsfiddle.net/94Dur/1/

The code should work when you run it from a file in your browser. 当从浏览器中的文件运行代码时,该代码应该可以工作。

I suspect that you have added the JavaScript before the <body> of your page. 我怀疑您在页面的<body>之前添加了JavaScript。 This would mean that the selector document.getElementById('confirm') is run before the page is loaded, meaning it wouldn't find the element, which again would result in the onchange -function not being added to the element. 这意味着选择器document.getElementById('confirm')在加载页面之前运行,这意味着它将找不到该元素,这又将导致onchange -function未添加到该元素。

You should try doing this: 您应该尝试这样做:

window.onload = function() {
    var checker = document.getElementById('confirm');
    var sbm = document.getElementById('sbmBtn');
    checker.onchange = function () {
        if(this.checked) {
            sbm.disabled = false;
        } 
        else {
            sbm.disabled = true;
        }
    } 
}

This will make sure that your JavaScript is not run until the content of the page has been loaded. 这将确保在加载页面内容之前不运行JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM