Marihuan
Marihuan

Reputation: 41

Javascript input value

I wanted to a make a function that after you enter anything in the input and press the button the alert box would say "value". And if you press the button and you haven't entered anything in the input the alert box would say "no value". Here is my code and it is not working. After I press the button, every time the alert box says "no value".

<body>
<input type="text">
<button onclick="btn()" type="button" name="button">submit</button>

<script type="text/javascript">

    var input = document.getElementsByTagName("input");
    function btn(){
      if (input.value = "none") {
        alert("no value");
      }else {
        alert("value");
      }
    }

</script>

Upvotes: 0

Views: 62

Answers (2)

dale landry
dale landry

Reputation: 8610

To be more specific you could declare an id in your element and use it so you do not have to reference the index of the tag. Otherwise you will need to reference the index of the tag as you are using getElementsByTagName().

Also as mentioned in the comment, the comparator is important.

= is used for assigning values to a variable.

== is used for comparing two variables, but it ignores the datatype of variable.

=== is used for comparing two variables, but this operator also checks datatype and compares two values.

var input = document.getElementById("myInput");

function btn() {
  if (input.value === "") {
    alert("no value");
  } else {
    alert(input.value);
  }
}
<input id="myInput" type="text">
<button onclick="btn()" type="button" name="button">submit</button>

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

You need to check the value of input[0] and use === to check for the value:

var input = document.getElementsByTagName("input");
function btn(){
     if (input[0].value === "") {
          alert("no value");
     }else {
          alert("value");
     }
}
<input type="text">
<button onclick="btn()" type="button" name="button">submit</button>

Upvotes: 2

Related Questions