【问题标题】:If checkbox unchecked disable upload button如果复选框未选中禁用上传按钮
【发布时间】:2012-06-23 07:11:47
【问题描述】:

我正在使用 valums 文件上传器。但我想启动一个复选框,如果用户没有选中它,则禁用上传按钮。

我可以让它以常规形式工作,但不使用值,因为我认为,他使用 div 元素作为表单属性。所以我猜我的代码搞砸了。

在 html 中我有:

<form class="well">
<label>Upload a Single File</label>
<label class="checkbox">
<input id="tos" onclick="if(this.checked){this.form.qq-upload-button.disabled=false}else{this.form.qq-upload-button.disabled=true};this.blur();" checked="" value="1" name="tos" type="checkbox"> I have read and agree to the <a href="/tos">TOS</a>
</label>
<div id="file-uploader-demo1">      
    <noscript>          
        <p>Please enable JavaScript to use file uploader.</p>
        <!-- or put a simple form for upload here -->
    </noscript>         
</div>
</form>

在 fileuploader.js 中(我有值代码)

template:   '<div class="qq-uploader">' + 
            '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
            '<div class="qq-upload-button btn btn-primary left">Upload a file</div><span class="help-inline">&nbsp;Lets Do it!</span>' +
            '<ul class="qq-upload-list"></ul>' + 
            '</div>',

你能看出我弄错了什么吗?

基本上,如果用户没有选中复选框,我希望禁用上传按钮。

对于常规形式,此代码有效:

<form class="well">
  <label>Upload a Single File</label>
  <input type="file" class="span3" placeholder="Click Here">
  <span class="help-inline">Associated help text!</span>
  <label class="checkbox">
  <input id="tos" onclick="if(this.checked){this.form.btn.disabled=false}else{this.form.btn.disabled=true};this.blur();" checked="" value="1" name="tos" type="checkbox"> I have read and agree to the <a href="/tos">TOS</a>
  </label>
  <input name="btn" type="submit" class="btn btn-primary left" value="UPLOAD">
</form>

【问题讨论】:

    标签: jquery


    【解决方案1】:

    删除内联 onclick 处理程序并添加以下 JavaScript 代码:

    $('#tos').on('change', function() {
        $('.qq-upload-button').prop('disabled', !this.checked);
    });
    

    这会将“禁用”状态与复选框的否定“选中”状态同步。

    您的原始代码不起作用的原因是 this.form.qq-upload-button 是无效的 JavaScript。您必须改用this.form['qq-upload-button']。但是,使用我上面发布的代码更加更简洁。

    【讨论】:

    • Thankyou @ThiefMaster ,所以我要摆脱 ?
    • +1 不错。但是.on() 真的需要吗? .change()不能用吗?
    • @422 去掉 onchange 属性即可。
    • @iambriansreed:从 jQuery 1.7+ 开始,这是最简洁和建议的方式。如果您愿意,可以使用.change(...) 代替.on('change', ...)
    • @iambriansreed:它不仅具有一致性,而且live() 从未真正被使用过,因为它有很多缺点。有关不同绑定的详细信息,请参阅此内容:stackoverflow.com/questions/11148019/…
    猜你喜欢
    • 2013-08-12
    • 2022-10-13
    • 2015-09-22
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多