Reputation: 311
With the code shown below, I would like to disable the text input when the user clicks on the button.
When I click on my button, the text input only disables for one second, before it enables again.
I would like to know why does this happens.
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$('#enable').click(function() {
$('#textBox').removeAttr("disabled")
});
$('#disable').click(function() {
$('#textBox').attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<form>
<input type="text" id="textBox" />
<button id="enable">Enable</button>
<button id="disable">Disable</button>
</form>
</body>
</html>
Upvotes: 1
Views: 2578
Reputation: 318192
A button inside a form submits the form, reloading the page, as it's default type is submit
.
You have to either change the type
<input type="button" id="enable" value="Enable">
or prevent the default
$('#enable').click(function (e) {
e.preventDefault();
$('#textBox').prop("disabled", false);
});
$('#disable').click(function (e) {
e.preventDefault();
$('#textBox').prop("disabled", true);
});
And use prop()
for the disabled property.
Upvotes: 3