1

I'm using jQuery to activate a function every time the user clicks on a button that has a certain class. I'm trying to get the value of the button clicked, and so far, failing.

window.onload = function() {
    $('.button').click(function(item) {
        console.log(item.value);
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button" value="7">7</button>

The expected result would be "7", since that is the value of the button. Currently, I'm getting undefined.

Thanks in advance!

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
Ivan Penev
  • 59
  • 5

4 Answers4

2

If your want to stick with using just JQuery, Use $(this).val() That should get you the value of the button.

change your JS to this:

$(document).ready (function() {
    $('.button').click(function(item) {
        console.log($(this).val());
    });
});

Try out this Jsfiddle as well to see if this is what you're looking for: https://jsfiddle.net/9zjLfso8/

Also if you're going to use jQuery, I would recommend that you use $(document).ready instead of window.onload. Here's a link to see the difference between the two: window.onload vs $(document).ready()

King11
  • 1,239
  • 3
  • 9
  • 17
2
window.onload = function() {
    $('.button').click(function(e) {
        console.log(e.target.textContent);
    });
}
Jay Kariesch
  • 1,392
  • 7
  • 13
2

basic one...

Pure jQuery:

$(document).ready(function() {
  $('.button').click(function(item) {
    console.clear();
    console.log( $(this).text(), ' = ', $(this).val() );
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button" value="7">bt 7</button>
<button class="button" value="8">bt 8</button>

Pure JS:

window.onload = function() {

  document.querySelectorAll('.button').forEach(bt=>{
    bt.onclick=e=>{
      console.clear()
      console.log(e.target.textContent,' = ', e.target.value) 
    }
  })
}
<button class="button" value="7"> bt 7 </button>

<button class="button" value="8"> bt 8 </button>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
1

You can do it with vanilla JavaScript:

   <button class="button" 
   onclick="myFunc(7)">7</button>

The script:

   function myFunc(value){
       console.log(value)
   }
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
bill.gates
  • 14,145
  • 3
  • 19
  • 47