Home > OS >  How do I compare user input to a variable?
How do I compare user input to a variable?

Time:10-19

I don't know how to make this work. Does anyone know how to fix this? I have tried multiple different solutions, but they don't work

function submit() {
  var user = "test";
  if (document.getElementById('#user').input = user) {
    //what I need help on
  }
}
function openForm() {
  document.getElementById("myForm").style.display = "block";
}

function closeForm() {
  document.getElementById("myForm").style.display = "none";
}
<button  onclick="openForm()">Open Form</button>

<div  id="myForm">
  <form action="#" >
    <h1>Login</h1>

    <label for="username"><b>username</b></label>
    <input type="text" placeholder="username" id="username" name="username" required>
    <button type="submit" onclick="submit()" >Login</button>
    // And here
    <button type="button"  onclick="closeForm()">Close</button>
  </form>
</div>

CodePudding user response:

First, where is user input element, that you mentioned in JavaScript, there is no input with id user, only one input with id username exist, use that and hashtag is not used for ids in document.getElementById replace

document.getElementById('#user')

to

document.getElementById('username') // use username and remove the hashtag (#)

Secondly, use value instead of input

document.getElementById('username').value

Returns the value (text) of the input element

Lastly, use == or === operators in statements not = in JavaScript.

Example

if (document.getElementById('username').value === user) { // Replaced = with ===
    //what I need help on
}

Full JavaScript Code

function submit() {
  var user = "test";
  if (document.getElementById('username').value === user) {
    //what I need help on
  }
}
function openForm() {
  document.getElementById("myForm").style.display = "block";
}

function closeForm() {
  document.getElementById("myForm").style.display = "none";
} 

CodePudding user response:

Use this instead

if(document.getElementById('#user').value == user)

I'd suggest you to store the input element in a variable first to dry your code ;)

CodePudding user response:

I see you got the wrong username id, try my code below:

function submit() {
    var user = "test";
    if (document.getElementById('#username').value == user) {
        //what I need help on
    }
}
  • Related