0

I have a really basic if else code that returns either "CORRECT" or "INCORRECT"

How do I format this text so that "CORRECT" appears GREEN & "INCORRECT" appears RED

???

<html>

<script language="javascript">
function QA1()
{
    var ANSWER = document.getElementById("ANSWER").value;
    var RESULT;
    if (ANSWER == '2') {
    RESULT = "CORRECT";
} else {
    RESULT = "INCORRECT";
} 
document.getElementById("RESULT1").innerHTML = RESULT;
}
</script>


<body>

<form method="post">
    <p><input type="text" length="3" id="ANSWER">&nbsp;&nbsp;
<input type="button" value="Enter" onclick="QA1()"></p>
</form>
<p id="RESULT1"></p>

</body>
</html>

2 Answers 2

1

Use the style.color property to modify the color of the element.

    function QA1()
    {
        var ANSWER = document.getElementById("ANSWER").value;
        var resultCorrect = ANSWER === '2' ? true : false;
        var result1 = document.getElementById("RESULT1");
        var color;
        var resultText;
        if(resultCorrect)
        {
           color = 'green';
           resultText = 'CORRECT';
        }
        else
        {
           color = 'red';
           resultText = 'INCORRECT';
        }

        result1.style.color = color;
        result1.innerHTML = resultText;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That seems to work everywhere except Wordpress which is where I need it unfortunately. Any idea why that might be? The old code worked on there but now it doesn't display the word or the color. Is it something about wordpress?
Is this a public site I can view to see for myself? Could be a plugin overwriting the inline style.
0

From the W3Schools documentation:

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property=new style 

The following example changes the style of a <p> element:

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

So you can do:

var element = document.getElementById("RESULT1");
element.innerHTML = RESULT;
element.style.color = RESULT === 'CORRECT' ? 'green' : 'red';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.