Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable / Enable button when the text and textarea are empty

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" />
like image 333
jovenne Avatar asked Nov 06 '13 07:11

jovenne


2 Answers

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" />
like image 158
rynhe Avatar answered Sep 25 '22 18:09

rynhe


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

like image 41
palaѕн Avatar answered Sep 25 '22 18:09

palaѕн