Xander
Xander

Reputation: 1011

How to clear a textarea value in jQuery?

I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.

I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");

Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.

EDIT:

Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.

HTML:

<textarea id="noteNumberInput" placeholder="Note number"></textarea>

JS:

var noteNumberInput = document.getElementById("noteNumberInput");

//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;
    //comparing pressed keycodes
    if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
        return true;
    }
    if (keycode < 48 || keycode > 57) {
        alert("Please only enter the note number e.g. 1, 2..14 etc.");
        $("#noteNumberInput").val("");
        return false;
    }
}

noteNumberInput.addEventListener("keydown", validate);

Upvotes: 1

Views: 1637

Answers (5)

Frank Wisniewski
Frank Wisniewski

Reputation: 1224

I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.

try this:

Element.addEventListener('input', function(){
    this.value=this.value.replace(/[^0-9,.]/g, '');
});

this must be adapted to textarea...

Upvotes: 0

Lucas Barbosa
Lucas Barbosa

Reputation: 1

Your only asking for the validate() function to actually execute when you've pressed the next key.

Upvotes: 0

brk
brk

Reputation: 50346

Using $("#noteNumberInput").val() will clear the textarea

EDIT

The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.

Change the keydown to keyup

var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);

DEMO

Upvotes: 1

webbm
webbm

Reputation: 653

Change noteNumberInput.addEventListener("keydown", validate); to use keyup

Upvotes: 1

dekts
dekts

Reputation: 830

When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.

Upvotes: 2

Related Questions