Peter Jordanson
Peter Jordanson

Reputation: 91

Button not responding to click with JQuery

So I'm new to JQuery and am trying to write a program which returns (console log for testing) the value of a button when it is clicked. For some reason my code does not register when the button is clicked, and additionally I don't think the right value is being parsed for the "car" parameter.

Here is my code (probably more than needed but not sure where I'm going wrong):

$(document).ready(function() {
  $(":button").click(myFunction(this.value));
});

function myFunction(car) {
  selection = car;
  console.log(selection);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" name="newButton" value="Mercedes"> <br>
<input type="button" name="newButton" value="BMW"> <br>
<input type="button" name="newButton" value="Audi">

I expect the program to log the value of the button that is pressed, however it is currently logging nothing.

Thanks

Upvotes: 0

Views: 47

Answers (2)

connexo
connexo

Reputation: 56843

This is very easy without any help of jQuery:

document.addEventListener('DOMContentLoaded', function() { // native way to do $(document).ready(function() {
  // get a list of all buttons and iterate over it
  for (const btn of document.querySelectorAll('input[type=button]')) {
    // and add a click listener to each one of them
    btn.addEventListener('click', function(event) {
      console.log(btn.value);  
    })
  }
})
<input type="button" name="newButton" value="Mercedes"> <br>
<input type="button" name="newButton" value="BMW"> <br>
<input type="button" name="newButton" value="Audi">

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

The problem is you are executing the function there. You should assign it, not execute it.

$(document).ready(function() {
  $(":button").click(myFunction);
});

function myFunction(event) {
  selection = event.target.value;
  console.log(selection);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" name="newButton" value="Mercedes"> <br>
<input type="button" name="newButton" value="BMW"> <br>
<input type="button" name="newButton" value="Audi">

You can use the above way, or better, this way:

$(document).ready(function() {
  $(":button").click(e => myFunction(e.target.value));
});

function myFunction(car) {
  selection = car;
  console.log(selection);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" name="newButton" value="Mercedes"> <br>
<input type="button" name="newButton" value="BMW"> <br>
<input type="button" name="newButton" value="Audi">

Upvotes: 4

Related Questions