Tuesday, February 14, 2012

jquery disable button

jquery version 1.7.1
All code run successful in platform such as chrome, firefox and ie.
1.How to disable the button use jquery?
2.How to check if button is disabled use jquery?
3.Demo for jquery disable button
3.1 disable the button when webpage initialize
3.2 onclick event disable button
3.3 disable submit button on form submit

1.How to disable the button use jquery?

There are two method disable the button using jquery.
the first way:
$("#xxx").attr("disabled",true);

the second way:
$("#xxx").attr("disabled","disabled");

Tip:
1.when we set the disabled property the html code will change to
<input id="xxx" type="button" value="Button" disabled="disabled">

2.The disabled property of JavaScript is a not null property,meaning it can take any string value.
document.getElementById("xxx").disabled = "true";
or
document.getElementById("xxx").disabled = "disabled";

3.Disabled <input> elements in a form will not be submitted.
4.The disabled attribute will not work with <input type="hidden">.

2.How to check if button is disabled use jquery?

In jQuery you can use the “is” function to check if the button is disabled like this:
   
if ($('#xxx').is(':disabled') == true) {}

The jquery "is" api please see http://api.jquery.com/is/

3.Demo for jquery disable button

3.1 disable the button when webpage initialize

Demo:


Below is the source code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#bid").attr("disabled","disabled");
});
</script>
</head>
<body>
<input id="bid" type="button" value="Target Button">
</body>
</html>

3.2 onclick event disable button

Demo:


Below is the source code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $("#cid").click(function(){
  $("#tid").attr("disabled","disabled");
 });
});
</script>
</head>
<body>
<input id="cid" type="button" value="Click Me">
<input id="tid" type="button" value="Target Button">
</body>
</html>

3.3 disable submit button on form submit

Demo:


Below is the source code:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#testform').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
    return false;//false, don't submit.
});
});
</script>
</head>
<body>
<form id="testform" action="your submit page url" method="get">
    <input name="username" />
    <!-- some more form fields -->
    <input id="submit" type="submit" />
</form>
</body>
</html>

No comments:

Post a Comment