Onclick change button text javascript

How to change the Button element text using JavaScript

In this tutorial, we are going to learn about how to change the text value of an button element using JavaScript.

Consider, we have a following input button element:

 input type="button" value="Red" id="btn" />

Now, we want to change the above button text value to blue by using JavaScript.

To change the button text, first we need to access the button element inside the JavaScript by using the document.getElementById() method and add a click event handler to the button, then set it’s value property to blue .

const btn = document.getElementById("btn"); btn.addEventListener("click", ()=> if(btn.value === "Red") btn.value = "Blue"; >else btn.value= "Red"; > >)

Now, when we click on our button , it changes the value from Red to Blue or vice versa.

If you want to change the text value for a HTML element, then you need to update the button element innerText property instead of value property.

const btn = document.getElementById("btn"); btn.addEventListener("click", ()=> if(btn.innerText === "Red") btn.innerText = "Blue"; >else btn.innerText= "Red"; > >);

Источник

Onclick change button text javascript

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Table of Contents

# Change button text on Click using JavaScript

To change the text of a button on click:

  1. Add a click event listener to the button.
  2. Use the textContent property to change the button’s text.
  3. For example, btn.textContent = ‘Button clicked’ .

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> button id="btn">Click mebutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const btn = document.getElementById('btn'); // ✅ Change button text on click btn.addEventListener('click', function handleClick() btn.textContent = 'Button clicked'; >); /** * ✅ If you need to change the button's inner HTML use: * - `innerHTML` instead of `textContent` */

We added a click event listener to the button.

Every time the button is clicked, the handleClick function is invoked.

The textContent property can be used to change the button’s text every time it’s clicked.

# Changing the button’s innerHTML on click

If you need to change the button’s inner HTML, use the innerHTML property instead of textContent .

Copied!
const btn = document.getElementById('btn'); // ✅ Change button text on click btn.addEventListener('click', function handleClick() const initialText = 'Click me'; btn.innerHTML = `span style="background-color: salmon">Button clickedspan>`; >);

This approach could be used to add a loading spinner when the user clicks a button.

Note that you shouldn’t set the button’s innerHTML based on user-provided input without escaping it. This would make your site vulnerable to cross-site scripting attacks.

# Toggle button text on Click using JavaScript

To toggle a button’s text on click:

  1. Add a click event listener to the button.
  2. Each time the button is clicked, check if the button’s text is the initial text.
  3. If it is, change the text to the clicked text.
  4. Otherwise, change the text back to the initial text.
Copied!
const btn = document.getElementById('btn'); // ✅ Toggle button text on click btn.addEventListener('click', function handleClick() const initialText = 'Click me'; if (btn.textContent.toLowerCase().includes(initialText.toLowerCase())) btn.textContent = 'Button clicked'; > else btn.textContent = initialText; > >); /** * ✅ If you need to change the button's inner HTML use: * - `innerHTML` instead of `textContent` */

Each time the button is clicked, the handleClick function is invoked.

In the function, we check if the button’s textContent contains the initial text value.

We converted both the initialText and the button’s text content to lowercase to make a case-insensitive comparison.

If the button’s text is the initial text, we set the text to a new value of Button clicked .

Otherwise, we set the button’s text to the initial text.

# Toggle a button’s innerHTML on click

If you need to use HTML when setting the button’s content, use the innerHTML property instead of textContent .

Copied!
const btn = document.getElementById('btn'); // ✅ Toggle button text on click btn.addEventListener('click', function handleClick() const initialText = 'Click me'; if (btn.textContent.toLowerCase().includes(initialText.toLowerCase())) btn.innerHTML = 'Button clicked'; > else btn.textContent = initialText; > >);

We used the innerHTML property to set the content of a button to a span with a background color.

In a more real-world scenario, you would probably set the content to some text and a loading spinner.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

JavaScript Change Button Text

Craving a more dynamic learning experience? we’ve crafted a comprehensive YouTube video complementing this article embedded at the end of this page!

JavaScript Change Button Text

We aim to learn about JavaScript change button text via example code. It shows how the button text changes on load, click, and mouseover. It also exemplifies the use of jQuery to change the button text.

JavaScript Change Button Text on Load

If you have HTML Element like input[type=’button’] or input[type=’submit’] then you can change button text in the following way.

input id="btn" type="button" value="Update"> input id="btnSubmit" type="submit" value="Update"> 
document.querySelector('#btn').value = 'Remove'; document.querySelector('#btnSubmit').value = 'Remove'; 

You can also change button text of HTML Element by using any of given methods below (given methods are .innerHTML , .innerText , and .textContent ).

button id="btn" type="button" value="Show Result">Show Resultbutton> button id="btnSubmit" type="submit" value="Submit Result">Submit Resultbutton> 
//querySelector selects the element whose id's value is btn  document.querySelector('#btn').innerHTML = 'Hide Result'; document.querySelector('#btn').innerText = 'Hide Result'; document.querySelector('#btn').textContent = 'Hide Result';  //querySelector selects the element whose id's value is btnSubmit  document.querySelector('#btnSubmit').innerHTML = 'Hide Result'; document.querySelector('#btnSubmit').innerText = 'Hide Result'; document.querySelector('#btnSubmit').textContent = 'Hide Result'; 

Can we use .innerHTML , .innerText , and .textContent for HTML element? No. The reason is is an empty element while is a container tag and has .innerHTML , .innerText , and .textContent properties.

  1. You may have to face cross-site security attacks due to using JavaScript .innerHTML .
  2. JavaScript .innerText reduces the performance because it needs details about the layout system.
  3. JavaScript .textContent does not arises any security concerns like .innerHTML . It also does not have to parse the HTML Content like .innerText which results in the best performance.

Now, you know the differences between them. So, choose any of these methods that suit your project requirements. You can read more about them here.

JavaScript Change Button Text on Mouseover

button class="button">Hide Resultbutton> 
.button   background-color: red; > .button:hover   background-color: green; > 
let btn = document.querySelector(".button");  btn.addEventListener("mouseover", function()   this.textContent = "Show Result!"; >) btn.addEventListener("mouseout", function()   this.textContent = "Hide Result"; >) 

The code above should show an output where the button’s text and color change when your mouse pointer hovers the button.

The querySelector() outputs the first element that matches the defined selector. The addEventListener() attaches an event handler to the given element and sets up a method for triggering a particular event.

We use mouseover and mouseout events, and the .textContent changes the button text.

JavaScript Change Button Text on Click

input onclick="changeText()" type="button" value="Hide Result" id="btn"> 
function changeText()  let element = document.getElementById("btn");  if (element.value=="Hide Result")  element.value = "Show Result";  else  element.value = "Hide Result"; > 

changeText() runs when you click on the button. This method gets the first element that matches the specified selector using getElementById() . Then, it checks the element’s value and changes according to the if-else statement.

JavaScript Change Button Text Using jQuery

 html>  head>  title>Change Texttitle>  script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">script>  head>  body>  button id="button" onclick="changeText()">Hide Resultbutton>  body>  html> 
function changeText()  $("#button").html('Show Result');  $("#button").css('background-color', 'green'); > 

The code above changes the button’s text from Hide Result to Show Result when you click on the button, and it also changes the button’s color to green.

The .html() sets the content of the selected element while .css() changes the background-color to green. Remember, .html() is used to for HTML element.

For more detail of these functions, check this link.

You might be thinking about how can we change the text using jQuery if we have HTML element? The following code is for you to understand.

 html>  head>  title>Change Texttitle>  script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">script>  head>  body>  input type="button" id="btnShow" value="Show" onclick="changeText()">  body>  html> 
function changeText()  $("#btnShow").attr('value', 'Hide'); //versions older than 1.6  $("#btnShow").prop('value', 'Hide'); //versions newer than 1.6  $("#btnShow").css('background-color', 'yellow'); > 

You can use .attr() or prop() (depending on jQuery version) to change the button text of HTML element. Both, .attr() and .prop() targets the value attribute of element and changes its value according to the second parameter.

In this sample code, the second parameter is Hide . The changeText() method also changes the background color to yellow using .css() function.

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article — JavaScript Button

Источник

Читайте также:  Message from user python
Оцените статью