user3340637
user3340637

Reputation: 43

Remove disable button if the textbox have values inside

can anyone help me how to remove button disable attribute if the the textboxes with class(number) have values inside and disable again if the textbox is empty.

current code:

<input type="text" name="name" class="number" value="hello" readonly />
<input type="submit" name="send" id="send" disabled />

script code:

<script type="text/javascript">
$('.number').on('input', function () {
    $('#send').prop("disabled", !$.trim(this.value));
});
</script>

Upvotes: 0

Views: 1106

Answers (5)

ChaoticNadirs
ChaoticNadirs

Reputation: 2290

try something like this

$('.number').on('change', function () {
    if ($(this.val() == '') {
        $('#send').removeAttr('disabled');
    } else {
        $('#send').attr('disabled', '');
    }
});

Upvotes: 0

Lix
Lix

Reputation: 47956

You could listen for keydown events and every time a key is pressed, you check the value of the element:

$( ".number" ).on( "keydown", function ( e ) {
    var current_value = $( this ).val();
    // The keypress event actually happens before the character is inserted. 
    var value = $.trim( current_value + e.which );
    if ( value.length > 0 ){
      $( "#send" ).attr( "disabled", false );
    }
});

The only problem with this approach is that it will not work if the user copy-pastes a value into the textbox. The alternative would be to use a setInterval to check the input every X seconds.

Upvotes: 0

fedevegili
fedevegili

Reputation: 371

Try it like this:

    /* The keyup event fires right after the user releases a key */
    $(".search-bar").on("keyup", function() {
        var state = this.value === "";
        $("#send").attr("disabled", state);
    })

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

Your current code works fine: JSFiddle demo.

The problem is that your .number element is set to readonly, meaning it doesn't accept any input (which is the event you're handling).

If you're setting the readonly property on the server side, I imagine you can also set the disabled property on the server side as well.

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

use:

 $('.number').keyup(function() {
    if($(this).val() != '') {
       $('#send').removeAttr('disabled');
    }else{
       $('#send').attr('disabled',true);
  }});

Upvotes: 2

Related Questions