Quantcast
Channel: สอน PHP สอนทำเว็บด้วย Joomla ระบบ CRM บทความ Hosting - สอน PHP สอนทำเว็บด้วย Joomla ระบบ CRM บทความ Hosting
Viewing all articles
Browse latest Browse all 24

Chapter 12 - JavaScript Conditions

$
0
0
Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

 

In JavaScript we have the following conditional statements:

 

if statement - use this statement to execute some code only if a specified condition is true

if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false

if...else if....else statement - use this statement to select one of many blocks of code to be executed

switch statement - use this statement to select one of many blocks of code to be executed

 

If Statements

A comparison that meet the criteria or not. If this is done under the order. If not, it will jump to the next command. The format is as follows: 

Syntax

if (condition) 
{/ / Statement}

Example:

<html>
<body>
<p>Click the button to get a "Good Morning" greeting if the time is less than 20:00.</p>
<button onclick="myFunction()">Click Here</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<20)
  {
  x="Good Morning";
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

This is the result:

 

If ...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.

 

Conditions using if ... else 

Defines options other than those specified in the if and if the conditions do not meet the conditions specified in the order if the application is made as stated in the following format else. 

Syntax

if (condition) 
 {/ / Case statement matches the condition}. 
else 
{/ / Case statement that does not meet the conditions}. 

Example:

<html>
<body>
<button onclick="myFunction()">Click Here</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

This is the result:

 

 

If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be executed.

Example:

<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<10)
  {
  x="Good morning";
  }
else if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

This is the result:

 

 

Next

{--mlinkarticle=2956--}Chapter 13 - JavaScript Switch{--mlinkarticle--}


Viewing all articles
Browse latest Browse all 24

Trending Articles