3

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?

2
  • It seems to work just fine: jsfiddle.net/Blender/XHUZ4 Commented Sep 28, 2012 at 7:29
  • Maybe relevant to show your HTML Commented Sep 28, 2012 at 7:33

3 Answers 3

4

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!)

Sign up to request clarification or add additional context in comments.

2 Comments

Yor are right @Praveen Kumar. I use the trim() method. But still it is not working. My trim() method is given below function trim(s) { return s.replace( /^\s*/, "" ).replace( /\s*$/, "" ); }
@user1407310 Is it possible for you to use jQuery?
3

Do check for white space in the value like this

if (problem_desc.value.match (/\S/)) { ... } 

or other way check for length

 problem_desc.value.length == 0; 

Comments

0

Remove spaces and calculate length of the value attribute.

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

    if (problem_desc.value.replace(/ /g,'').length) {
       return true;
    } else {
       alert("Please Write Problem Description");
       return false;
    }
}
<textarea id="problem_desc"></textarea>
<button onclick="validateForm()">Validate</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.