简体   繁体   中英

Change Button value on click without id or class

Let's suppose my button is as follows:

<input type="button" value="BLUE" name="button_blue" />

What I want is when I click the button, value="BLUE" should be changed to value="RED" or anything I want.

Use val() method:

$('button').on('click',function(){
  $(this).val('RED');
});

To change it's previous value on click again:

$('button').on('click',function(){
  $(this).val($(this).val() == 'RED' ? 'BLUE' : 'RED');
});

You can solve this completely without jQuery:

<input id='button' type="button" value="BLUE" name="button_blue" />

javascript:

document.getElementById('button').onclick = function(){
    this.value = 'red';
};

Demo: http://jsfiddle.net/jg1hjk1u/

try this code

$('button').on('click',function(){
  $(this).val($(this).val() == "RED" ? "BLUE" : "RED")
  //OR
  //this.value = this.value == "RED" ? "BLUE" : "RED";
});

Since the button has name="button_blue" attribute, use Attribute Equals Selector

$('[name=button_blue]').on('click',function(){
  $(this).val('RED');
});

Working demo: http://jsfiddle.net/dw8kmh3g/

First add an id to the button -

<input type="button" id="myColorButton" value="BLUE" name="button_blue" />

Then add the following piece of code to your script -

document.getElementById("myColorButton").onclick = function() {
    this.value="RED";
};

I would just create a separate CSS class:

.button{
background-color:red;
}

And then add the class on click:

$('#button').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('button') : '';
});

You can also create the ability to have an "on/off" switch feel by toggling the class:

<button id="button">Hello</button>

here working link: this jsfiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM