Disable / Enable button when the text and textarea are empty

20,672

Solution 1

You miss the textarea selector in jQuery

$(document).ready(function() {
    $('input[type="submit"]').attr('disabled', true);
    
    $('input[type="text"],textarea').on('keyup',function() {
        var textarea_value = $("#texta").val();
        var text_value = $('input[name="textField"]').val();
        
        if(textarea_value != '' && text_value != '') {
            $('input[type="submit"]').attr('disabled', false);
        } else {
            $('input[type="submit"]').attr('disabled', true);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="textField" /><br>
<textarea rows="4" cols="30" id="texta"></textarea><br>
<input type="submit" value="next" />

Solution 2

You can do this using the .prop() method like:

// Cache the elements first
var $text = $('input[type="text"]');
var $textarea = $('textarea');
var $submit = $('input[type="submit"]');

// Set the onkeyup events
$submit.prop('disabled', true);
$text.on('keyup', checkStatus);
$textarea.on('keyup', checkStatus);

// Set the event handler
function checkStatus() {
    var status = ($.trim($text.val()) === '' || $.trim($textarea.val()) === '');
    $submit.prop('disabled', status);
}

F.Y.I.

As mentioned in the .prop() API Documentation:

Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.


FIDDLE DEMO

Share:
20,672
jovenne
Author by

jovenne

Updated on December 28, 2020

Comments

  • jovenne
    jovenne over 3 years

    I have this code that disable the button when the text is empty, but I have a textarea html code. How can I include this that when the text and textarea are both empty the button will be disabled and when both are filled it enables. I tried the code below and it works on text only. Any ideas?

    $(document).ready(function() {
        $('input[type="submit"]').attr('disabled', true);
        
        $('input[type="text"]').on('keyup',function() {
            if($(this).val() != '') {
                $('input[type="submit"]').attr('disabled', false);
            } else {
                $('input[type="submit"]').attr('disabled', true);
            }
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="text" name="textField" />
    <textarea rows="4" cols="30" ></textarea>
    <input type="submit" value="next" />