João Silva João Silva - 2 months ago 6
HTML Question

jquery get array of buttons and their values

Im new in JS and Jquery.
I have been trying to set an event to all buttons in the same class, meanwhile I'm tryinh to get the value of each button.

In my HTML I got:

<div id="highlightButtons">
<button type="button" class="btn btn-primary" value="1">1</button>
<button type="button" class="btn btn-primary" value="2">2</button>
<button type="button" class="btn btn-primary" value="3">3</button>
<button type="button" class="btn btn-primary" value="4">4</button>
<button type="button" class="btn btn-primary" value="5">5</button>
<button type="button" class="btn btn-primary" value="6">6</button>
<button type="button" class="btn btn-primary" value="7">7</button>
<button type="button" class="btn btn-primary" value="8">8</button>
<button type="button" class="btn btn-primary" value="9">9</button>
</div>


And in my JS I tried this:

(function() {
'use strict'
var all_hl_btns = $('#highlightButtons');
all_hl_btns.click(function(){
var value = $(this).text();
alert(value);
});
}());


At this point, I'm just trying get the value of each button that I click, but when I click in any button, I got a text of numbers (1 to 9) in a Column.
I would appreciate any kind of help.
Thank you in advance!

Answer

You trying to add click event to #highlightButtons and when you click on it, javascript get text of it that is 123456789. You need to add click event to buttons. In the case, your selector changed to $('#highlightButtons > button')

(function() {
    'use strict'
    var all_hl_btns = $('#highlightButtons > button');
    all_hl_btns.click(function(){
        var value = $(this).text();
        alert(value);
    });
}());

var all_hl_btns = $('#highlightButtons > button');
all_hl_btns.click(function(){
  var value = $(this).text();
  console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="highlightButtons">
      <button type="button" class="btn btn-primary" value="1">1</button>
      <button type="button" class="btn btn-primary" value="2">2</button>
      <button type="button" class="btn btn-primary" value="3">3</button>
      <button type="button" class="btn btn-primary" value="4">4</button>
      <button type="button" class="btn btn-primary" value="5">5</button>
      <button type="button" class="btn btn-primary" value="6">6</button>
      <button type="button" class="btn btn-primary" value="7">7</button>
      <button type="button" class="btn btn-primary" value="8">8</button>
      <button type="button" class="btn btn-primary" value="9">9</button>
    </div>