简体   繁体   中英

alert box not working properly in JavaScript

<script>
    function fun(){
          let i=document.getElementById("input")
          if(i==="sam")
            {
               alert("welcome SAM")
            }
          else
            {
               alert("welcome user")
            }
        }
      </script>
     
        <input id="input"/>
        <button onclick="fun()">click</click>

if user type input as 'sam' it should be follow the if block but every time it execute else part.how to change the condition that when user type 'sam' in textbox then only it follow if block or else execute else part

getElementById method returns html element, if you want to get text inside input you should use document.getElementById("input")?.value

  1. Make sure your input is correct.

  2. Instead of writing "if(i===sam)", write "if(i=="sam").

  3. Other than that, I think there's a problem with your input method. Javascript doesn't directly get the input from the box. For further information, check this link: https://www.tutorialspoint.com/How-to-take-user-input-using-HTML-forms

  4. If you want to do it the easier way, just put "document.getElementById("input").value"

If this answer helped you, please mark it as an answer

Just add .value ahead of document.getElementById("input")

Just like that:

let i=document.getElementById("input").value

Basically, you're not passing the text to the variable i that is the reason else is executing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM