Home Programming Thorough explanation of how to do HTML conditional branching with JavaScript!

Thorough explanation of how to do HTML conditional branching with JavaScript!

by Yasir Aslam
0 comment

You want to change the HTML display content depending on the conditions, but you wonder if HTML has such a function.

JavaScript if statements and switch statements are used to conditionally branch HTML.

In this WEBCAMP MEDIA, we will explain how to do HTML conditional branching with JavaScript.

  • How to load JavaScript
  • Syntax for conditional branching
  • Conditional branch method

I will explain the above items.

By reading this article, you can understand how to conditionally branch the contents of HTML using JavaScript. By using conditional branching, you can create dynamic websites that are easy for users to use, so be sure to check it out!

Table of contents

  • How to load JavaScript in HTML
    • load external javascript files
    • write directly to the HTML file
  • JavaScript syntax used for conditional branching in HTML
    • Features of the if statement
      • Conditional branch using only if statements
      • Conditional branch with else added to if statement
      • Conditional branch with else if added to if statement
    • Features of the switch statement
      • How to use the switch statement
  • How to conditionally branch HTML with JavaScript
    • Operate conditional branching with buttons
    • Operate display/hide of HTML by conditional branching
    • Realize multiple conditional branches by nesting if statements
  • summary

How to load JavaScript in HTML

The script tag is used to load JavaScript in an HTML file.

A script tag is a type of HTML tag that allows you to directly enter JavaScript or load an external file.

I will explain two ways to read JavaScript in HTML using the script tag.

load external javascript files

This is a method to load an external JavaScript file with an HTML file.

Enter the following code in the body tag of the HTML file.

<script type="text/javascript" src="test.js"></script>

The type attribute specifies the type of document to read, so enter “text/javascript” and enter the path to the file in the src attribute.

Recommended when you want to use an external JavaScript file for conditional branching.

write directly to the HTML file

You can also enter and execute JavaScript within the script tag.

The input method is as follows.

<script type="text/javascript">
    JavaScript
</script>

Just enter the JavaScript code inside the script tag and it will run.

This method is suitable for those who want to complete the implementation using only HTML files.

JavaScript syntax used for conditional branching in HTML

There are two ways to conditionally branch HTML code: the if statement and the switch statement in JavaScript.

I will explain each feature and how to use it.

Features of the if statement

An if statement is a type of function that can be used in JavaScript, and can conditionally branch depending on the content of the code, such as “if A, then B otherwise”.

By using the if statement, you can change the contents of the HTML code and display it according to the user’s operation.

There are three ways to enter an if statement, as shown below.

  • Conditional branch using only if statements
  • Conditional branch with else added to if statement
  • Conditional branch with else if added to if statement

I will explain each item in detail.

Conditional branch using only if statements

The input method of the if statement is as follows.

Enter the conditional branch condition in the argument of the if statement, and enter the processing to be executed in the syntax if it is true. If false, no processing is performed.

Conditional branch with else added to if statement

else can specify the processing when the result is false for the condition specified in the if statement.

The way to write if statement with else is as follows.

By adding else, you can add execution processing whether the content of the condition is true or false.

Conditional branch with else if added to if statement

else if can add a second condition when the condition specified in the if statement is false.

The writing method of adding else if to the if statement is as follows.

Adding an else if expands the range of conditional branching by allowing you to use two contents of the condition.

Please use different if statements depending on what you want to implement.

Features of the switch statement

A switch statement is a syntax that compares multiple cases for a specific condition and executes the processing entered in the matched cases.

The switch statement is useful for conditional branching by presenting multiple options for one condition.

How to write a switch statement is as follows.

Enter the value to be the target of the conditional branch in the argument of the switch statement. Enter the content to be compared with the condition in [case] in the switch statement.

Enter the processing when the condition is matched directly under each case, and specify break; at the end to complete.

How to use the switch statement

I will explain how to use the switch statement as an example of how to conditionally branch according to the color like a traffic light.

sample code

var color = ;
switch (color){
  case "":
    console.log(")
    break;
  case "":
    console.log(")
    break;
  case "":
    console.log("")
    break;
  default:
   
}

In the above code, the character “blue” is entered in the color variable as a condition for the switch statement.

Since the process is executed when it matches the contents specified in the case, the process “go forward” entered in “blue” above is executed.

How to conditionally branch HTML with JavaScript

We will explain how to conditionally branch the contents of HTML using JavaScript, using practical cases as examples.

I will explain using sample code, so please check it out if you are a programming beginner or want to copy and paste and use it immediately!

Operate conditional branching with buttons

We will explain how to conditionally branch the contents of HTML by pressing a button and change the display contents using sample code.

In the sample code below, “OK” and “NG” radio buttons are installed, and the method for outputting different results depending on what is checked is described.

sample code

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
        <title></title>
    </head>
    <body>
  <form name="outline">
    <input type="radio" name="btn" value="ok">OK
    <input type="radio" name="btn" value="ng" checked>NG
    <input type="button" value="Check" onClick="btnCheck()">
    </form>
    <div id="text"></div>
    <script type="text/javascript">
        function btnCheck() {
          var check = document.outline.btn[0].checked;
          var output = document.getElementById("text");
          if (check) { //tureの
            output.innerHTML = "「OK」;
          } else { //false
            output.innerHTML = "「NG」す";
          }
        }
    </script>
</body>
</html>

The checked attribute is specified for NG of the input tag that creates the radio button, and it plays the role of a trigger that determines whether it is OK or NG.

In the process below, the state of btn[0], which is the name attribute of the radio button, is obtained and assigned to the check variable.

var check = document.outline.btn[0].checked;

By specifying checked, it will be a process that returns true and false whether the radio button is checked or not.

The if statement is branched so that if the check variable is true, “OK is selected” is displayed, and if it is false, “NG is selected” is displayed.

Operate display/hide of HTML by conditional branching

By using the if statement, it is possible to display or hide the characters created in HTML.

I will explain how to conditionally branch the display / non-display of HTML using sample code.

sample code

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
    <title></title>
</head>
<body>
  <p id="test" style="display: block;"></p>
  <input type="button" value="" onclick="btnClick()" />
  <script type="text/javascript">
        function btnClick(){
          test = document.getElementById("test");
            if(test.style.display == "block"){
              // none
              test.style.display = "none";
            }else{
              // block
              test.style.display = "block";
          }
      }
</script>
</body>
</html>

Using the getElementById function, the information of the displayed HTML tag is obtained and assigned to the test variable.

In the if statement, check the CSS content specified in the test variable with the style attribute. If it is “display:block;”, the element is displayed, so change it to “display:none;” with the style function to hide it.

Conversely, if it is “display:none”, specify “display:block;” in the else conditional branch to display the HTML element.

With the above processing, the HTML element is alternately displayed and hidden each time the button is pressed.

Realize multiple conditional branches by nesting if statements

You can also set multiple conditions by entering an if statement inside a JavaScript if statement. Inputting an if statement within an if statement is called “nesting” or “nesting”.

I will explain how to use nested if statements to process numbers entered in HTML with multiple conditional branches and output the results.

The content below is a code that branches the numerical value specified in the input field with multiple conditions, and the HTML output content changes for each result.

sample code

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
        <title>タイトル</title>
    </head>
    <body>
      <input type="number" id="num" max="10" min="1"/>
      <input type="button" value="クリック" onclick="clickBtn()" />
      <p id="result"></p>
      <script type="text/javascript">
          function clickBtn() {
              const num = document.getElementById("num");
              var num2 = num.value;
              var output = document.getElementById("result");
                  if (num2 > 5) {
                      if (num2 > 8) {
                          output.innerHTML = 
                      }
                  }else{
                      output.innerHTML = 
              }
          }
    </script>
    </body>
</html>

The input tag is used to create a number input field and a button that executes JavaScript.

Set the minimum and maximum values ​​of numbers that can be entered using the max and min attributes in the input tag that creates the input field for numbers. The onclick attribute is specified in the input tag that creates the button, and it is linked with the clickBtn function of JavaScript.

In the JavaScript code, the numerical value specified in the input field is acquired, stored in a variable called num2, and specified in an if statement for conditional branching.

The first if statement compares the number stored in the num2 variable with 5. If it is greater than 5, it goes to the conditional branch of the next nested if statement.

In this way, it is possible to narrow down the conditions by nesting if statements.

If you can use multiple if statements, the range of conditional branching will expand, so it’s a good idea to remember this article.

summary

This time, I explained how to do HTML conditional branching with JavaScript. How was it?

You can conditionally branch your HTML code by using JavaScript’s if and switch statements.

If you use conditional branching to change the display content or display sentences according to the situation, the website will become easier for users to use, so please try it out!

You may also like

Leave a Comment