-1

Sample:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Check Text Field Value</title>
    <style>
    </style>
</head>

<body>
    <textarea rows="5" cols="35" id="field" oninput="indicate();"></textarea>
    <div id="indicator"></div>
    <script>
        function indicate() {
            var field = document.getElementById('field');
            var indicator = document.getElementById('indicator');
            if (field.value) {
                indicator.innerHTML = 'Some content';
            } else {
                indicator.innerHTML = 'No content';
            }
        }
        indicate();
    </script>
</body>

</html>


Demo: http://jsfiddle.net/RainLover/eZaRd/

I want to check if the text field is empty or not. I've seen many questions and answers some using if (textarea.value) and some using if (textarea.value != ""). Or the following pair:
if (!textarea.value) vs. if (textarea.value == "").

I wonder what's the difference between them.

Mori
  • 8,137
  • 19
  • 63
  • 91
  • 3
    `if (textarea.value = "")` is a bug. The two other ones are equivalent. – Denys Séguret Feb 11 '14 at 09:28
  • 1
    After edit : the three tests are equivalent. But any search on SO would have told it. – Denys Séguret Feb 11 '14 at 09:30
  • @dystroy Incidentally, that's why a lot of people make a habit of putting the literal before the variable, as in: `if ("" == some.variable)` or `if (0 == x)`. It looks strange at first, but when you mistype an equal sign you will get a nice error, instead of all hell breaking loose. – Tobia Feb 11 '14 at 10:19
  • @dystroy: Many thanks for the comments! Just wanted to make sure they are the same in my example. :) – Mori Feb 11 '14 at 15:40

1 Answers1

1

If you just write if (textarea.value), it will return true for all the truthy values of the text area. For all the falsy values it will return false like NaN, undefined, null or "" In other case if (textarea.value = ""), it will return true only if the value of the text area is "".

You should use !! operator to check for both scenarios (undefined and empty) as follows: if (!!textarea.value)

Kop4lyf
  • 4,520
  • 1
  • 25
  • 31
  • How can the textarea value in my example be null, undefined or NaN? Would you mind giving an example? – Mori Feb 11 '14 at 10:55
  • We faced it once. But I am unable to remember the scenario. Other scenario is , if it is unable to find your element, then also it will return undefined like $("#not-found-id").val(); – Kop4lyf Feb 11 '14 at 11:31