Смена кнопки в javascript

Изменить значение кнопки с помощью JavaScript/jQuery

В этом посте мы обсудим, как изменить значение элемент типа button или submit в JavaScript и jQuery.

1. Использование jQuery

С помощью jQuery вы можете использовать .val() метод для установки значений элементов формы. Чтобы изменить значение элементы типа button или типа submit (т.е. или же ), вы можете сделать так:

JS

HTML

CSS

В качестве альтернативы вы можете использовать jQuery .prop() метод.

JS

HTML

CSS

2. Использование JavaScript

С помощью JavaScript вы можете изменить атрибут value элементов, который содержит DOMString используется в качестве метки кнопки.

JS

HTML

CSS

Вот и все, что касается изменения значения кнопки в JavaScript и jQuery.

Средний рейтинг 4.03 /5. Подсчет голосов: 36

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Смена кнопки в 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.

Источник

как изменить текст кнопки js

Для изменения текста кнопки в JavaScript необходимо получить доступ к элементу кнопки с помощью метода document.getElementById() , затем установить текстовое значение. Например, через свойство textContent :

const button = document.getElementById('myButton'); button.textContent = 'Новый текст кнопки'; 

В этом примере мы получили элемент кнопки по его id , затем установили новое значение свойства textContent на «Новый текст кнопки». Кнопка теперь будет отображать этот текст.

Чтобы изменить текст на кнопке с помощью JavaScript, можно использовать свойство innerHTML элемента кнопки. Вот пример:

Нажми меня  

В этом примере, сначала находим кнопку с помощью метода getElementById() , а затем используем свойство innerHTML для изменения текста кнопки на «Кликни меня». Это заменит текст «Нажми меня» на кнопке на новый текст «Кликни меня».

Также можно использовать метод innerText вместо innerHTML , если нужно изменить только текстовое содержимое элемента кнопки без изменения любых HTML-тегов внутри этого элемента. Вот пример:

Нажми меня  

Оба примера изменят текст на кнопке на новый текст. Выбор между использованием innerHTML или innerText зависит от того, нужно ли изменять только текстовое содержимое элемента или изменять HTML-теги внутри элемента кнопки.

Источник

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

Источник

Читайте также:  Элемент select в HTML5
Оцените статью