Reputation: 927
I have this simple jQuery code to test out.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("text").attr("disabled","");
});
});
</script>
</head>
<body>
<input type="text">
<br />
<button>Set the textfield disabled</button>
</body>
</html>
Basically the HTML page comes with a simple button and textfield. All I want to have the input field disabled as I click the button. But it doesn't work???
(PS: this code is sourced out from w3schools.com website, just to simply test out how powerful jQuery is)
Upvotes: 14
Views: 35067
Reputation: 150253
There is not text
selector in jquery
. You need to use the attribute selector [attribute=value]
$('input[type=text]').prop('disabled', true); // prop Works on jquery 1.7+
or:
$('input[type=text]').attr('disabled', 'disabled'); // Works in each version.
// But isn't W3C standard.
there is a :text
selector but it's less efficent then the first option, see the docs:
$(':text') is equivalent to $('[type=text]') and thus selects all elements. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("") is implied. In other words, the bare $(':text') is equivalent to $(':text'), so $('input:text') should be used instead.
Additional Notes: Because :text is a jQuery extension and not part of the CSS specification, queries using :text cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use [type="text"] instead.
Note that your's XHTML isn't valid. You should close the <input type="text">
=> <input type="text" />
Upvotes: 1
Reputation: 282825
"disabled" is a property, not an attribute per-se. Booleans like "checked" or "disabled" don't always get updated (or retrieved) properly when accessing them that way. Use
$(':text').prop('disabled',true);
instead.
Upvotes: -1
Reputation: 351
Try this:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("#text").attr("disabled","true");
});
});
</script>
</head>
<body>
<input id="text" type="text">
<br />
<button>Set the textfield disabled</button>
</body>
</html>
Upvotes: 2
Reputation: 160833
From jQuery 1.7, you could use .prop
:
$(document).ready(function(){
$("button").click(function(){
$(":text").prop("disabled", true);
});
});
Before 1.7, you could do:
$(document).ready(function(){
$("button").click(function(){
$(":text").attr("disabled", true);
});
});
PS: Use $(":text")
or $('input[type="text"]')
to select all elements of type text.
Upvotes: 18
Reputation: 16544
Or (more modern):
$("input[type=text]").prop('disabled', true);
Upvotes: 1