How do I change the class of a button according to its id and value?

Asked

Viewed 817 times

0

I intend to modify the class of a button according to its id and its value. Each <button> has equal identifiers, but different values.

I tried this way below, however only the first button is modified, independent of the value that is inserted for the variable value. For this case below you should modify the class referring to the button with text MARCELEZA.

var value = 4;
$("#month").val(value).attr('class', 'btn btn-primary btn-xs');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet"/>
<div style="margin: 20px">
  <button id="month" type="button" class="btn btn-default btn-xs" value="1">BALACO BACCO</button>
  <button id="month" type="button" class="btn btn-default btn-xs" value="2">CAPTÃO G.NASCIMENTO</button>
  <button id="month" type="button" class="btn btn-default btn-xs" value="3">JBUENO'S DIA</button>
  <button id="month" type="button" class="btn btn-default btn-xs" value="4">MARCELEZA</button>
</div>

How can I change the class of a button according to its id and value?

1 answer

6


You can use selector [value=X]:

var value = (Math.floor(Math.random() * 4) + 1); // << Para explicar gera um número qualquer, clique em "Executar" para selecionar um diferente.

$("#month button[value='" + value + "']").attr('class', 'btn btn-primary btn-xs');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet"/>
<div id="month" style="margin: 20px">
  <button type="button" class="btn btn-default btn-xs" value="1">BALACO BACCO</button>
  <button type="button" class="btn btn-default btn-xs" value="2">CAPTÃO G.NASCIMENTO</button>
  <button type="button" class="btn btn-default btn-xs" value="3">JBUENO'S DIA</button>
  <button type="button" class="btn btn-default btn-xs" value="4">MARCELEZA</button>
</div>

For convenience, to avoid repetitions of id, I used the id directly on div, in this way it is possible to search for button which has the value within the div with such id.


#month button[value='3']

That query, if so may be called, will find any element with the id equal to month and then find the button, son of month, that the value equal to 3.

  • It was not I who denied :/

  • Anyway, I made changes to remove the repetition of id also. ;)

  • 3

    Inkelizmente you answered well and first of all, already have the upvote guaranteed, I think that’s what the AP is looking for.

  • Thanks, it worked beauty!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.