Khakwani
Khakwani

Reputation: 70

How to remove innerHTML value to be shown initially

I am trying to create a multiplication table in JavaScript. The user is prompted to provide the Table number (1 to 10) after which all the question marks ('?') are replaced with that number. The user then needs to enter the answers in all the provided text fields. Finally, the user will have the option to check the answer (i.e. whether it is right or wrong).

When I run my code. After entering the user data to prompt it shows Incorrect infront of each textfield and the user entered value just before the Check answers button. How can I remove them to be shown initially.

Output: My code:

function result() {
    var value = document.getElementById("a1").value;
    var checkMessageSpan1 = document.getElementById("checkMessage1");
    var checkMessageSpan2 = document.getElementById("checkMessage2");
    var r = x * 1;
    if (value == x) {
    checkMessageSpan1.innerHTML = "<span style=\"color:green\">"+"Correct!";
    }else{
    checkMessageSpan1.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
    }



    var value = document.getElementById("a2").value;
    var r = x * 2;
    if (value == r) {
    checkMessageSpan2.innerHTML = "<span style=\"color:green\">"+"Correct!";
    }else{
    checkMessageSpan2.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
    }


</script>
<button onClick="alert_field()"> Generate Question</button><br><br>

<p id="s1">
? x 1 = <input type="text"  id="a1"><span id="checkMessage1"></span><br>
? x 2 = <input type="text"  id="a2"><span id="checkMessage2"></span><br>

</p><br><br>
<p id="a"></p>

Check answers

Upvotes: 1

Views: 86

Answers (2)

muzzi
muzzi

Reputation: 372

Try to add this code:

var value = document.getElementById("a1").value;
if (checkMessageSpan1.style.display === "none") {
    checkMessageSpan1.style.display = "inline-block";
} else {
    checkMessageSpan1.style.display = "none";
}

var value = document.getElementById("a2").value;
if (checkMessageSpan2.style.display === "none") {
    checkMessageSpan2.style.display = "inline-block";
} else {
    checkMessageSpan2.style.display = "none";
}

Upvotes: 1

gurpreet singh chahal
gurpreet singh chahal

Reputation: 370

For replacing all special characters, you may leverage regular expressions in js var res=str.replace(/[^a-zA-Z0-9]/g,x); instead of var res = str.replace("?",x);

More on Regular expressions in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Upvotes: 2

Related Questions