JavaScript > Conditional Statements

If statement in JavaScript

How to write if statement in JavaScript?


If statement is used to execute a block of statements only when certain condition is met.

<script>
          function Check() {
              var myName = document.getElementById("txtName").value;

              // if block
              if (myName == "Sheo") {
                  alert("Yes");
              }

              // if else block
              if (myName == "Sheo") {
                  alert("Yes");
              }
              else {
                  alert("No");
              }

              // if else if else block
              if (myName == "Sheo") {
                  alert("Yes");
              }
              else if (myName == "Sheo Narayan") {
                  alert("Yes");
              }
              else {
                  alert("No");
              }
          }
</script>

    Enter your name: <input type="text" id="txtName" /> 
    <input type="button" id="btnSubmit" value="Check my name" onclick="Check()" />

Above code snippet gives “Yes” alert. Here else or else if blocks are optional.

 Views: 1067 | Post Order: 25



Write for us