dr-amira dr-amira - 1 year ago 67
Javascript Question

The if condition always return true

please help here: the if condition always return true though it is false??
these are the html code for variable div and variable your at the beginning

(<div class="div" id="div" style="background:yellow"></div>)
(<input type="text" id="your">)

$(document).ready(function generate() {
"use strict";
var x = $(".2").text(Math.floor((Math.random() * 10))),
z = $(".3").text(Math.floor((Math.random() * 10)));

$(".div").text(x.text() + z.text());
});



var show = document.getElementById("show"),
your = document.getElementById("your").value,
div = document.getElementById("div").textContent;
show.onclick = function () {
"use strict";
if (your == div) {
alert("yes");
} else {
alert("noo");
}
};

Answer Source

The problem is, that you are defining the values outside of the function. So in the onclick handler you are comparing the initial values.

If you want the actual values, you should access the values inside the function:

var show = document.getElementById("show"),
    your = document.getElementById("your"),
    div = document.getElementById("div");

show.onclick = function () {
    if (your.value == div.textContent) {
        alert("yes");
    } else {
        alert("noo");
    }
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download