Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 290
awongCM Avatar asked Jan 27 '12 07:01

awongCM


People also ask

How do I disable a field in HTML?

To make a table in HTML, use the <table> tag. Within this table tag, you'll place the <tr>, <th>, and <td> tags. The <tr> tag defines a table row. The <th> tag defines the table header.

How do I set disabled property in jQuery?

The disable/enable an input element in jQuery can be done by using prop() method. The prop() method is used to set or return properties and values for the selected elements. Example 1: This example uses prop() method to disable the input text field.

How check textbox is disabled or not in jQuery?

You can use $(":disabled") to select all disabled items in the current context. To determine whether a single item is disabled you can use $("#textbox1").is(":disabled") . Save this answer.

How do I disable a textbox?

We can easily disable input box(textbox,textarea) using disable attribute to “disabled”. $('elementname'). attr('disabled','disabled'); To enable disabled element we need to remove “disabled” attribute from this element.


1 Answers

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.

like image 165
xdazz Avatar answered Oct 26 '22 22:10

xdazz