Raihan
Raihan

Reputation: 4001

Remove Disable attribute if there are value on the Inputs

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:

  1. Button will be disabled very first. If click on the input it will be active.
  2. if there is no value made on the input and click outside button will be disable.
  3. But if any value has been added button will remain active. It will not make disable state.

JSFIDDLE .

Thanks In advance.

Upvotes: 1

Views: 1080

Answers (3)

ramchauhan
ramchauhan

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

MattD
MattD

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");
     }
 });

FIDDLE

Upvotes: 4

isherwood
isherwood

Reputation: 61063

$('input[name="firstName"]"]').focus(function() { 
   $(".update-change").removeAttr('disabled');
}).blur(function() {
    if ($(this).val() == '') {
        $(".update-change").attr('disabled', 'disabled');
    }
});

Upvotes: 2

Related Questions