Disable/enable an input with jQuery?

2018-12-31 01:37发布

$input.disabled = true;

or

$input.disabled = "disabled";

Which is the standard way? And, conversely, how do you enable a disabled input?

16条回答
人气声优
2楼-- · 2018-12-31 02:23

There are many ways using them you can enable/disable any element :

Approach 1

$("#txtName").attr("disabled", true);

Approach 2

$("#txtName").attr("disabled", "disabled");

If you are using jQuery 1.7 or higher version then use prop(), instead of attr().

$("#txtName").prop("disabled", "disabled");

If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.

Approach 1

$("#txtName").attr("disabled", false);

Approach 2

$("#txtName").attr("disabled", "");

Approach 3

$("#txtName").removeAttr("disabled");

Again, if you are using jQuery 1.7 or higher version then use prop(), instead of attr(). That's is. This is how you enable or disable any element using jQuery.

查看更多
无色无味的生活
3楼-- · 2018-12-31 02:23

Use like this,

 $( "#id" ).prop( "disabled", true );

    $( "#id" ).prop( "disabled", false );
查看更多
几人难应
4楼-- · 2018-12-31 02:23
<html>
<body>

Name: <input type="text" id="myText">



<button onclick="disable()">Disable Text field</button>
<button onclick="enable()">Enable Text field</button>

<script>
function disable() {
    document.getElementById("myText").disabled = true;
}
function enable() {
    document.getElementById("myText").disabled = false;
}
</script>

</body>
</html>
查看更多
美炸的是我
5楼-- · 2018-12-31 02:24

Update for 2018:

Now there's no need for jQuery and it's been a while since document.querySelector or document.querySelectorAll (for multiple elements) do almost exactly same job as $, plus more explicit ones getElementById, getElementsByClassName, getElementsByTagName

Disabling one field of "input-checkbox" class

document.querySelector('.input-checkbox').disabled = true;

or multiple elements

document.querySelectorAll('.input-checkbox').forEach(el => el.disabled = true);
查看更多
登录 后发表回答