Home > Software engineering >  How to compare two values from input text?
How to compare two values from input text?

Time:10-19

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');}" >
 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>

CodePudding user response:

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

CodePudding user response:

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">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related