2

I have abutton in my page and I want to disable it. Is there a way to do it? my code is as follows

<script type="text/javascript"> $(document).ready(function() { var myButton = $(this, "input[type='button']"); $(myButton).attr("disabled", "true"); }); </script> <input id="create" class="button" type="button" > 

5 Answers 5

6

Change

$(myButton).attr("disabled", "true"); 

to

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

When you want to re-enable it

$("#create").removeAttr("disabled"); 
Sign up to request clarification or add additional context in comments.

3 Comments

Unless he's using an ancient version of jQuery, using .prop() to set the boolean value would be much better.
Please elaborate on much better. I wasn't aware of the .prop() method. Is it recommended over attr()?
Using .prop() is like setting element.something with element being the DOM element. .attr() is like calling element.setAttribute(...). While for disabled both works, it will not work for things such as the value of form elements (even though you'll want to use .val() for those anyway)
2

Use .prop() to set the disabled property of the button:

myButton.prop('disabled', true); 

Note that myButton is already a jQuery object, so you do not need $() around it again. To enable the button again, simply use myButton.prop('disabled', false);

Your selector to create myButton is wrong, too. Use this instead:

var myButton = $("input[type='button']"); 

or even better select it by its ID (faster and also works if you have multiple buttons in your page):

var myButton = $('#create'); 

So, to keep it short and simple, use the following:

$('#create').prop('disabled', true); 

Comments

1
$('#create').attr("disabled", "disabled"); 

Comments

0
var $myButton = $("input#create"); $myButton.click(function(e) { e.preventDefault(); if($(this).hasClass("disabled")) { // do NOT submit } else { // submit } }); // somewhere else... $myButton.addClass("disabled"); 

And use some CSS styling to make the button appear disabled (i.e. opacity: 0.4 and/or make it grey or something).

2 Comments

Do not use something#id but rather just #id - an id needs to be unique anyway so it's unlikely that you have the same id on another element.
@ThiefMaster: I used it mainly for the semantics so that people reading the above snippet would always know it'd be a certain input element.
-1

I'd use

$('#create').attr("disabled", true); 

without the quotes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.