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>
Roman Meyer
  • 2,634
  • 2
  • 20
  • 27
  • Obviously make sure popups are enabled in whatever browser used, and of course javascript itself. Try making an unconditional alert, and see if that works – JosephDoggie Jun 04 '19 at 14:50
  • 1
    Possible duplicate of [How do I get the value of text input field using JavaScript?](https://stackoverflow.com/questions/11563638/how-do-i-get-the-value-of-text-input-field-using-javascript) – Heretic Monkey Jun 04 '19 at 14:52

2 Answers2

4

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

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
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>
Mario
  • 374
  • 2
  • 9