2

I want alert to pop if input letters length is equal to 0 but it is not working

<div class="rame">
    <input type=text placeholder="Name" style="position: relative; right:-750px" id="inp1">
    <input type=text placeholder="Name2" style="position: relative; right:-250px" id="inp2">
    <button onclick="check()">submit</button>
</div>

<script>
    function check() {
        var a = document.getElementById("inp1");
        var b = document.getElementById("inp2");
        if (a.length = 0) {
            alert("Hello World")
        }
    }
</script>
2

2 Answers 2

4

You should call if(a.value.length==0). Note the difference between = and ==.

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

3 Comments

or even better to use joda notation. if (0 == a.value.length) { ... } and then you'll never face this kind of misspell error headache
@RomanBobrik yoda notation :-) Let's use postfix aritmetic operators then :-)
no kidding, it is useful thing to avoid misspelling in conditions. saved a lot of time for me
2
  1. With getElementById you will get an ELEMENT
  2. In pure JavaScript length is meant for strings
  3. If you want to compare you have to use double =

I think you tried this:

<div class="rame">
        <input type=text placeholder="Name" style="position: relative; right:-750px" id="inp1">
        <input type=text placeholder="Name2" style="position: relative; right:-250px" id="inp2">
        <button onclick="check()">submit</button>
    </div>

    <script>
        function check() {
            var a = document.getElementById("inp1");
            var b = document.getElementById("inp2");
            if (a.value.length == 0) {
                alert("Hello World")
            }
        }
    </script>

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.