Reputation: 43
Can anyone help me how to make my button disable if my texbox
suddenly filled with text without clicking the textbox to input something.
My problem is my code wont work. Does anyone know how to do it.
<form method="post">
<input type="text" name="name1" id="name1" class="number" />
<input type="text" name="name2" id="name2" class="number" />
<input type="submit" name="send" id="send" class="hey" value="one" disabled />
</form>
script code:
<script>
$(document).ready(function () {
$('.number').blur(function () {
if ($.trim(this.value) == "") {
$('#send').attr("disabled", true);
}
else {
$('#send').removeAttr("disabled");
}
});
});
</script>
Upvotes: 3
Views: 180
Reputation: 38112
If you want to make sure the button is only enable when the two textbox are filled, then you can do:
function doCheck() {
var allFilled = true;
$('input[type=text]').each(function () {
if ($(this).val() == '') {
allFilled = false;
return false;
}
});
$('input[type=submit]').prop('disabled', !allFilled);
}
$(document).ready(function () {
$('input[type=text]').keyup(doCheck);
});
Upvotes: 0
Reputation: 148178
Use keyup
instead of blur
and prop()
instead of attr()
The blur is triggered when input gets or loose focus. The prop should be use for boolean attributes like checked disabled etc.
$('.number').keyup(function () {
if ($.trim(this.value) == "") {
$('#send').prop("disabled", true);
}
else {
$('#send').prop("disabled", false);
}
});
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, reference.
Upvotes: 0
Reputation: 193301
You can use combination of input, blur and keyup events to be safe:
$('.number').on('keyup blur input', function () {
$('#send').prop("disabled", !$.trim(this.value));
});
Upvotes: 3
Reputation: 7240
$('.number').keyup(function () {
if ($.trim(this.value) == "") {
$('#send').addAttr('disabled');
}
else {
$('#send').removeAttr('disabled');
}
});
Upvotes: 1