Javascript как изменить кнопку

This wikiHow article will teach you how to change the button color once it's clicked using JavaScript. Changing the button color lets users know that they have already clicked the button on your page. Open your project in a Java-editing...


Download Article


Download Article

This wikiHow article will teach you how to change the button color once it’s clicked using JavaScript. Changing the button color lets users know that they have already clicked the button on your page.

Steps

  1. Image titled 12779919 1

    1

    Open your project in a Java-editing environment. This can be anything like Visual Studio or Oracle JDeveloper.

  2. Image titled 12779919 2

    2

    Enter the following code into your program to change the button’s color with onclick:

    <script>
    
    document.getElementById("changeGreen").onclick = function(){
    	document.getElementById("output").style.color = 'green';
    }
    
    document.getElementById("changeRed").onclick = function(){
    	document.getElementById("output").style.color = 'red';
    }
    </script>
    
    • This code prompts the buttons to change the color of your text from green to red. You can replace these colors with others you prefer.[1]

    Advertisement

  3. Image titled 12779919 3

    3

    Enter the following code into your program if you want to change the button’s color when a text field is filled in:

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
    </head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
    <body>
       <label>
          UserName:
       </label>
       <input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px"
          onkeyup="changeTheColorOfButtonDemo()">
       <br><br>
       <button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>
    </body>
    <script>
       function changeTheColorOfButtonDemo() {
          if (document.getElementById("changeColorDemo").value !== "") {
             document.getElementById("buttonDemo").style.background = "green";
          } else {
             document.getElementById("buttonDemo").style.background = "skyblue";
          }
       }
    </script>
    </html>
    
    • Using an <IF/ELSE> statement, the button is skyblue until the input field is filled, then it changes to a green button.
    • If you want to change the colors, you can either use color names like «Green» or «Skyblue,» Hexadecimal numbers (which you can find by searching Hexadecimal colors), or RGB colors (which you can also find by a simple internet search). To change the colors in the code, replace the «green» and «skyblue» colors in the code style.background.
  4. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

References

About This Article

Article SummaryX

1. Open your project in a Java-editing environment.

2. Enter the following code into your program to change the button’s color with «onclick.»
3. Enter the following code into your program if you want to change the button’s color when a text field is filled in.

Did this summary help you?

Thanks to all authors for creating a page that has been read 16,601 times.

Is this article up to date?


Download Article


Download Article

This wikiHow article will teach you how to change the button color once it’s clicked using JavaScript. Changing the button color lets users know that they have already clicked the button on your page.

Steps

  1. Image titled 12779919 1

    1

    Open your project in a Java-editing environment. This can be anything like Visual Studio or Oracle JDeveloper.

  2. Image titled 12779919 2

    2

    Enter the following code into your program to change the button’s color with onclick:

    <script>
    
    document.getElementById("changeGreen").onclick = function(){
    	document.getElementById("output").style.color = 'green';
    }
    
    document.getElementById("changeRed").onclick = function(){
    	document.getElementById("output").style.color = 'red';
    }
    </script>
    
    • This code prompts the buttons to change the color of your text from green to red. You can replace these colors with others you prefer.[1]

    Advertisement

  3. Image titled 12779919 3

    3

    Enter the following code into your program if you want to change the button’s color when a text field is filled in:

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Document</title>
    </head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
    <body>
       <label>
          UserName:
       </label>
       <input type="text" id="changeColorDemo" style="margin-left:10px;margin-top:10px"
          onkeyup="changeTheColorOfButtonDemo()">
       <br><br>
       <button id="buttonDemo" style="background:skyblue;margin-left:10px;">Press Me</button>
    </body>
    <script>
       function changeTheColorOfButtonDemo() {
          if (document.getElementById("changeColorDemo").value !== "") {
             document.getElementById("buttonDemo").style.background = "green";
          } else {
             document.getElementById("buttonDemo").style.background = "skyblue";
          }
       }
    </script>
    </html>
    
    • Using an <IF/ELSE> statement, the button is skyblue until the input field is filled, then it changes to a green button.
    • If you want to change the colors, you can either use color names like «Green» or «Skyblue,» Hexadecimal numbers (which you can find by searching Hexadecimal colors), or RGB colors (which you can also find by a simple internet search). To change the colors in the code, replace the «green» and «skyblue» colors in the code style.background.
  4. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

References

About This Article

Article SummaryX

1. Open your project in a Java-editing environment.

2. Enter the following code into your program to change the button’s color with «onclick.»
3. Enter the following code into your program if you want to change the button’s color when a text field is filled in.

Did this summary help you?

Thanks to all authors for creating a page that has been read 16,601 times.

Is this article up to date?

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

The button элемент теперь является предпочтительным способом создания кнопок над <input> элемент типа кнопка. Существует несколько способов изменить buttonтекст метки , который вставляется между открывающим и закрывающим тегами.

С помощью jQuery вы можете использовать .text() метод, чтобы заменить buttonтекст ярлыка . Это показано ниже:

JS

$(document).ready(function() {

    $(‘#submit’).click(function() {

        $(this).text(‘Processing…’);

    })

});

HTML

<!doctype html>

<html lang=«en»>

    <body>

    <button id=«submit»>Submit</button>

    </body>

</html>

Изменить в JSFiddle

 
Обратите внимание, что .text() будет экранировать предоставленный текст, если это необходимо для правильного отображения в HTML.

 
В качестве альтернативы вы можете использовать jQuery .html() метод для полной замены содержимого элемента новым содержимым. Он использует возможности браузера innerHTML свойство и не экранирует предоставленный текст, что приводит к межсайтовым атакам безопасности.

JS

$(document).ready(function() {

    $(‘#submit’).click(function() {

        $(this).html(‘Processing…’);

    })

});

HTML

<!doctype html>

<html lang=«en»>

    <body>

    <button id=«submit»>Submit</button>

    </body>

</html>

Изменить в JSFiddle

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

В чистом JavaScript вы можете использовать либо innerHTML, innerText или же textContent чтобы написать текст внутри элемента. Среди них, textContent имеет более высокую производительность, поскольку его значение не анализируется как HTML, а также предотвращает атаки XSS.

JS

document.getElementById(‘submit’).onclick = function() {

    this.textContent = ‘Processing…’;

}

HTML

<!doctype html>

<html lang=«en»>

    <body>

    <button id=«submit»>Submit</button>

    </body>

</html>

Изменить в JSFiddle

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

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

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

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

  1. JavaScript Change Button Text on Load
  2. JavaScript Change Button Text on Mouseover
  3. JavaScript Change Button Text on Click
  4. JavaScript Change Button Text Using jQuery

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 <input> Element like input[type='button'] or input[type='submit'] then you can change button text in the following way.

HTML Code:

<input id="btn" type="button" value="Update">
<input id="btnSubmit" type="submit" value="Update">

JavaScript Code:

document.querySelector('#btn').value = 'Remove';
document.querySelector('#btnSubmit').value = 'Remove';

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

HTML Code:

<button id="btn" type="button" value="Show Result">Show Result</button>
<button id="btnSubmit" type="submit" value="Submit Result">Submit Result</button>

JavaScript Code:

//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 <input> element? No. The reason is <input> is an empty element while <button> is a container tag and has .innerHTML, .innerText, and .textContent properties.

Though the goal is achieved by using .innerHTML, .innerText, and .textContent, you must have certain points in your mind.

  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

HTML Code:

<button class="button">Hide Result</button>

CSS Code:

.button {
 background-color: red;
}
.button:hover {
 background-color: green;
}

JavaScript Code:

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

HTML Code:

<input onclick="changeText()" type="button" value="Hide Result" id="btn">

JavaScript Code:

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 Code:

<!DOCTYPE>
<html>
 <head>
 	<title>Change Text</title>
 	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 </head>
 <body>
 	<button id="button" onclick="changeText()">Hide Result</button>
 </body>
</html>

JavaScript Code:

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 <button> 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 <input> element? The following code is for you to understand.

HTML Code:

<!DOCTYPE>
<html>
 <head>
 	<title>Change Text</title>
 	<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>

JavaScript Code:

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 <input> element. Both, .attr() and .prop() targets the value attribute of <input> 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.

Понравилась статья? Поделить с друзьями:
  • Javascript try catch error object
  • Javascript sql error
  • Javascript promise throw error
  • Javascript parsing error
  • Javascript nan ошибка