Rajesh
Rajesh

Reputation: 123

Trying to disable button when input text field is empty

I am having an input text field and a button. When the text field is empty the button should disable. when the field is filled the button should be enable. I tried with the following code but not working properly help me!

$(document).ready(function(){
$("#wmclrsrch").attr("disabled", "disabled");

if ( $('#search_number').is(":empty") ) {
    alert ("verdadeiro");
    $("#wmclrsrch").attr("disabled", true);
}
$('#wmsearch').click(function(){
    $("#wmclrsrch").attr("disabled", false);
    $("#wmclrsrch").attr("enabled", true);
});

});

The HTML is:

<form id="form">
   <label for="search_number">Mobile Number:</label>
   <input id="search_number" type="text" />
   <button id="wmclrsrch">Clear Search</button>
</form>

Thanks in Advance,

Upvotes: 0

Views: 906

Answers (3)

user1589583
user1589583

Reputation: 1

You can try the following script:

<script>
/*
 *
 * A tiny jQuery plugin that could control the button's state
 *
 * code from https://github.com/jvyyuie/snbutton
 *
 */
var SNButton = {
    init: function(e) {
        var snnode = "#"+$("#"+e).data("snnode");
        $("#"+e).attr("disabled", ""==$(snnode).val());
        $(snnode).on('input propertychange', function() {
            $("#"+e).attr("disabled", ""==$(snnode).val());
        });
    }
}
</script>

<input id="textinput" />
<button id="btn" data-snnode="textinput">Button</button>

<script>
SNButton.init("btn");
</script>

It is a very simple jquery plugin that disables button when some input filed is empty.

Upvotes: 0

Ram
Ram

Reputation: 144739

You can listen the keyup event and use prop method.

$(document).ready(function(){ 
    $('#search_number').keyup(function(){
        $("#wmclrsrch").prop("disabled", !this.value.length);    
    }).keyup();
});

Upvotes: 1

sdespont
sdespont

Reputation: 14025

Check input text using keyup event :

$('#search_number').keyup(function(){
    if($(this).val() != '')
    {
        //Eneable your button here
    }
    else
    {
        //Disable your button here
    }
});

Upvotes: 0

Related Questions