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

0

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

I have tried this way below, however only the first button is modified, regardless of the value that is entered for the value variable. For this case below you should modify the class for the MARCLE text button.

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><scriptsrc="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?

    
asked by anonymous 27.01.2017 / 15:43

1 answer

6

You can use [value=X] selector:

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><scriptsrc="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 id replication, I used id directly on div , so you can search for button that has the value inside div with such id . / p>

#month button[value='3']

This query, if so called, will find any element with id equal to month and then find button , child of month , that value that is equal to 3 .

    
27.01.2017 / 15:48