简体   繁体   English

Javascript启用已禁用的文本框

[英]Javascript enable already disabled text box

i am trying to create a form where a text field loads up disabled, and if the user wants to input into this field they have to click a check box. 我正在尝试创建一个禁用了文本字段加载的表单,如果用户想在此字段中输入内容,则必须单击一个复选框。 I have this at the moment. 我现在有这个。

However with what is below the text box loads up enabled and ticking the check box will disable it. 但是,在下面的文本框中启用了加载功能,勾选此复选框将禁用它。 How can this be modified so this is reversed. 如何对此进行修改,以便将其反转。 ie the text box is first disabled and clicking the check box enables it? 即首先禁用文本框,然后单击复选框启用它?

Javascript code JavaScript代码

$(document).ready(function () {
            $('#testcheckbox').change(function() {
                $('#testtextfield').attr('disabled', this.checked);
            });
        });

HTML code HTML代码

<input type="checkbox" id="testcheckbox" />
<input type="text" id="testtextfield" />

Thanks. 谢谢。

Try using this setup: 尝试使用此设置:

<input type="checkbox" id="testcheckbox" />
<input type="text" id="testtextfield" disabled="disabled" />

$(document).ready(function () {
    $('#testcheckbox').change(function() {
        $('#testtextfield').prop('disabled', !this.checked);
    });
});

http://jsfiddle.net/93HJ3/ http://jsfiddle.net/93HJ3/

In this case, the textbox is disabled by default. 在这种情况下,默认情况下将disabled文本框。 Then, when clicking on the checkbox, the textbox is disabled based on its inverted checked property, for the opposite behavior you wanted. 然后,在单击复选框时,基于文本框的反转checked属性,将禁用该文本框,以实现所需的相反行为。

If you look at http://api.jquery.com/prop/ , you'll see that it is the jQuery method more accepted for changing elements' properties like "disabled", "readonly", "checked", etc. And a good discussion about the differences: .prop() vs .attr() . 如果您查看http://api.jquery.com/prop/ ,您会发现它是jQuery方法,更常用于更改元素的属性,例如“ disabled”,“ readonly”,“ checked”等。很好地讨论了区别: .prop()和.attr() But it's really up to you if you need to be changing the attribute or property, as they have different meanings. 但是,如果您需要更改属性或属性,则实际上取决于您,因为它们具有不同的含义。

Pure JavaScript equivalent if you don't want to use jQuery. 如果您不想使用jQuery,则可以使用纯JavaScript等效。

<input type="text" id="inputbox" diasbled="disabled" />

var inputbox = document.getElementById('inputbox');

document.addEventListener('DOMContentLoaded',function(){
    inputbox.removeAttribute('disabled');
});

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

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