Aim: Program on the concept of changing the label in javascript

Aim: Program on the concept of changing the label in javascript

Aim: Program on the concept of changing the label in javascript

Requirement :

  1. Working PC or Laptop ,
  2. Installed any operating system
  3. Any browser (Google Chrome)
  4. Any code Editor(VS Code)

Theory

There are many ways you can change the text of an element dynamically using a small script at the client side. I am sharing two different examples here in this post showing how to change the text of a label on button click using JavaScript or jQuery. To change the label text I need a value. Since I want to change the label text on button click, I’ll add a button on my webpage. The click events are used differently in both JavaScript and jQuery.

I also have a textbox (input type text) control, which will provide the value for the label.

Given an HTML document and the task is to change the text of a label using JavaScript.

What is a label ? The tag is used to provide a usability improvement for mouse users i.e, if a user clicks on the text within the element, it toggles the control.

Example Change the label value of an option in a drop-down list:

document.getElementById("myOption").label = "newLabel";

Property Values

Description : Specifies a shorter version for the option

Technical Details

Return Value: A String, representing the label of the option in the drop-down list. If the label attribute is not specified, it will return the

Change Label Text on Button Click using JavaScript

The first example is in JavaScript, where I am using two different properties to change the text of a label. The properties are innerText and innerHTML. You can learn the difference between the two properties here.

I said I have a button and a textbox on my web page. The button’s click event will call a function. In that function I’ll get the value from the textbox and assign the value the label using the properties I have mentioned above.,

Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />

    <style>
        .bg-salmon {
            background-color: salmon;
        }
    </style>
    <script>
        function handleClicked(e) {

            const label = document.getElementById('label');
            const first_name = document.getElementById('first_name');

            // ✅ Change (replace) the text of the label
            label.textContent = 'Enter Last name?';
            first_name.value = '';
        }
    </script>
</head>

<body>
    <h1>Practical No 06</h1>
    <div>
        <label id="label" for="first_name">Enter first name?</label>
        <input type="text" name="first_name" id="first_name" />
        <button id="handleClick" onClick={handleClicked()}>Enter</button>
    </div>
    <!-- <script src="index.js"></script>    -->
</body>

</html>

Conclusion: Finally, we can conclude that we have successfully programmed on the concept of changing the label in javascript.