Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate a textarea using javascript

Tags:

javascript

I want to check a textarea whether it is empty or not. For this I write the following code:

function validateForm(theForm) {
    var problem_desc = document.getElementById("problem_desc");

    if (problem_desc.value == '') {
        alert("Please Write Problem Description");
        return false;
    } else {
        return true;
    }
}​

For the first time it is working fine. But If I remove the text from the textarea the above function is returning true value i.e., it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?

like image 719
user1407310 Avatar asked Mar 02 '26 06:03

user1407310


1 Answers

I am getting it correctly. This is what I did.

  1. Click on validate, it said Please Write Problem Description.
  2. Write something and click. Nothing happened.
  3. Remove the text. Click on validate, it said Please Write Problem Description.

Note: Use a trim function to eliminate empty spaces.

Code:

function validateForm(theForm) {
    var problem_desc = document.getElementById("problem_desc");

    if ($.trim(problem_desc.value) == '') {
        alert("Please Write Problem Description");
        return false;
    } else {
        return true;
    }
}

Demo: http://jsfiddle.net/TZGPM/1/ (Checks for Whitespaces too!)

like image 163
Praveen Kumar Purushothaman Avatar answered Mar 03 '26 21:03

Praveen Kumar Purushothaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!