Reputation: 4001
I have a Input and submit button
<input type="text" name="firstName" placeholder="Michael">
<button type="button" class="update-change" disabled="disabled">Save</button>
I want when someone sets focus on the input the button will be active. So I used this:
$('input[name="firstName"]"]').focus(function() {
$(".update-change").removeAttr('disabled');
}).blur(function() {
$(".update-change").attr('disabled', 'disabled');
});
and because of this When anyone click outside button become disable again. This is Good so far but I am wanting when value is given on the input save button will not become disable clicking outside of the input. but I am not sure how to do this. Use change function ?
So points are:
JSFIDDLE .
Thanks In advance.
Upvotes: 1
Views: 1080
Reputation: 238
You can use if statement to check if the input is not having any thing then you are disabling the button other wise it remain enabled. Here is working demo
$('input[name="firstName"]').focus(function() {
$(".update-change").removeAttr('disabled');
}).blur(function() {
if($('input[name="firstName"]').val() == ""){
$(".update-change").attr('disabled', 'disabled');
}
});
Upvotes: 1
Reputation: 4420
On your .blur
function, you can check to see if it's empty. If it is, disable the button, else enable it. This will also enable the button if the focus is on the box, and disable it if focus is removed and nothing was typed in the box.
$('input[name="firstName"]').focus(function () {
$(".update-change").removeAttr('disabled');
}).blur(function () {
if ($.trim(this.value) == "") {
$('.update-change').attr("disabled", true);
} else {
$('.update-change').removeAttr("disabled");
}
});
Upvotes: 4
Reputation: 61063
$('input[name="firstName"]"]').focus(function() {
$(".update-change").removeAttr('disabled');
}).blur(function() {
if ($(this).val() == '') {
$(".update-change").attr('disabled', 'disabled');
}
});
Upvotes: 2