user10579402
user10579402

Reputation:

trying to check whether string is empty or not, but the check doesn't work properly

I am trying to check whether the textarea isn't empty. If yes: Then disable the submit button, if not: then enable it. However whenever I do back-space it disables the button (you could argue that it checks on keydown whether it's empty or not, and when it is it disables), so let's say that isn't even a big of a problem... However when I write something in my textarea it doesn't enable the submit button, it keeps it disabled with the first letter, when I press a second key it "recognizes" that the input isn't empty and enables it.

How the 2 functions look like:

function chatArea(tracker) {
    let textArea = ($('<textarea/>', {
        'col': 50,
        'row': 4,
        'class': 'form form-control',
        'name': 'textareaSubmitData',
        'id': 'textareaSubmitData',
        'maxLength': 200,
        'placeholder': 'Hey there! Feel free to start chatting!'
    })).on('keydown', function() {
        tracker.chatString = $(this).val();

        if($(this).val() == '') {
            $('#submitBtnTextArea').attr('disabled', 'disabled');
            return;
        } else {
            $('#submitBtnTextArea').removeAttr('disabled');
        }
    });
        return textArea;
    }

function submitBtnTextArea(tracker) {
    let btn = ($('<button/>', {
        'type': 'submit',
        'class': 'btn btn-success',
        'name': 'submit',
        'id': 'submitBtnTextArea'
    })).html('<li class="fa fa-send"> Send!</li>');
    return btn;
}

Any reason why it disables and enables without a logical reason behind it?

Upvotes: 3

Views: 53

Answers (1)

Gabitu
Gabitu

Reputation: 179

I think you should use keyup in this case.

Keydown is triggering before actually deleting the character from the textarea, so when you execute the anonymous method, the letter is still there. That's why when you enter the first character, the button is still disabled because there are 0 characters. When you enter a new character, then there is 1 character, and the button becomes enabled.

Upvotes: 3

Related Questions