Simple Javascript to change display content based on variable

hi,

I'm new to javascript but familiar with programming.

I want to change what's displayed on a simple webpage depending on a variable, what's a simple way to do this?

In VBA I could write, for example:

myPoints = 1

Select Case myPoints

    Case 0
        Debug.Print "You have no points."
    Case 1
        Debug.Print "You have just 1 point."
    Case Else
        Debug.Print "You have " & myPoints & " points."
End Select

Open in new window


Thanks
xeniumAsked:
Who is Participating?
 
MishaConnect With a Mentor ProgrammerCommented:
try this:

<script type="text/javascript">
var myPoints = 2;
switch(myPoints) 
{
 case 0:
           alert("You have no points.");
           break;
case 1:
         alert("You have just 1 point.");
        break;
default:
        alert ("You have " + myPoints  + " points.");
}

    </script> 

Open in new window

0
 
xeniumAuthor Commented:
Great thanks, that works fine.

I adapted it to write to the page:

<script type="text/javascript">
var myPoints = 2;

switch(myPoints) 
{
 case 0:
           myMessage = "You have no points.";
           break;
 case 1:
           myMessage = "You have just 1 point.";
           break;
 default:
           myMessage = "You have " + myPoints  + " points.";
}

document.write(myMessage);

</script> 

Open in new window



For my info, other ways to output: https://www.w3schools.com/js/js_output.asp
0
 
xeniumAuthor Commented:
For the record, example using document.getElementById(id)

<p id="myMessage"></p>


<script type="text/javascript">
var myPoints = 2;

switch(myPoints) 
{
 case 0:
           myMessage = "You have no points.";
           break;
 case 1:
           myMessage = "You have just 1 point.";
           break;
 default:
           myMessage = "You have " + myPoints  + " points.";
}

document.getElementById("myMessage").innerHTML = myMessage;

</script> 

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.