How can I disable the HTML textfield using this simple jQuery?

awongCM picture awongCM · Jan 27, 2012 · Viewed 30k times · Source

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)

Answer

xdazz picture xdazz · Jan 27, 2012

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.