简体   繁体   中英

How to compare two values from input text?

what's wrong with my code? The true alert never comes out even if I put a right answer,0414. Only false alert comes out.

 var answer = String(document.getElementById('Properdate').value); var rightanswer = '0414';
 <input id="Properdate" type="text"> <input type="submit" value="submit" onclick="if(answer === rightanswer){ alert('good'); } else { alert('Try again');}" >

I think it is becouse you are retrieving the value only when the page loads, when the event called it uses the value stored in answer which is the one it saved when page loaded.

<input id="Properdate" type="text">
<script>
var rightanswer= '0414';
</script>
<input type="submit" value="submit" onclick="
var answer = String(document.getElementById('Properdate').value);
if(answer === rightanswer){
 alert('good');
}
else{
alert('Try again');}"
 >

Should work with this

It's not a good idea to put the code as an onclick on the button! I made an example which I hope will be useful to you.

Example:

 document.getElementById('sbmt').addEventListener('click', submitFunc); function submitFunc() { var answer = document.getElementById('Properdate').value; var rightanswer = '0414'; if (answer === rightanswer) { alert('good'); } else { alert('Try again'); } }
 <input id="Properdate" type="text"> <input id="sbmt" type="submit" value="submit">

Try using a button tag since you are not submitting a form. Give it an ID so you can reference it from your JS file.

HTML

<input id="properdate" type="text">
<button id="submit" type="button">Submit</button>

From you JS file or tag. The "let" keyword lets you work with the variable in scope, you can declare it once and use it in different blocks and with different values.

Select your "submit" button element and use "addEventListener()" instead of the onclick attribute. This does not overwrite existing event handlers as the "onclick" does. From there, make sure you are using the correct event, in this case "click" and create a function to do whatever you need to. Use your if clauses and try to be as clean as possible. Keep working on that, pal!

JS

<script>
    let answer = document.getElementById('properdate');
    let rightanswer = '0414';
    let submit = document.getElementById('submit');

    submit.addEventListener('click', function(){
        if(answer.value === rightanswer) {
            alert('Good');
        } else {
            alert('Try again');
        }
    });
</script>

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