0

im trying to get a lil project going but im stuck on a very annoying thing.

$(document).ready(function() {
  $("#search-button").click(console.log('hello'))
});

as you can see im targeting a search button with the id search-button and as soon as i click it something should happen. in this case i put a console.log in to test if it works but it doesn't. it always logs it as soon as i load the page , not when i click the button i target. ... what am i doing wrong if you need more info on this pls tell me i tried to keep it as simple as i could

ty for your help

O.k

4 Answers 4

1

The click handler needs a function argument, not just the console.log by itself. Try this:

$(document).ready(function() {
  $("#search-button").click(function() {
      console.log('hello');
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Inside of .click should be a handler .click(handler) and the handler should be a function. The browser is reading the code and when it hits console.log('hello'), it does it! It's seeing .click etc, but it doesn't matter; it next sees console.log and does it.

Try

$(document).ready(function() {
  $("#search-button").click(function() {
    console.log('hello');
  });
});

Comments

0

As others have mentioned, the click function requires its own callback function. You can also use this, without requiring the use of document:

$("#search-button").on('click', function() {
    console.log('hello')
    })

Comments

0

I hope You're using jQuery version 3 or up. if you use 3 or up jquery version the good practice is you use Document binding Example:

jQuery(document).on('click', '#search-button', function(event) {
    //your Code here...
    console.log('hello');
 });

1 Comment

jQuery(document).on('event'... use for dynamically event binding. element. click event or normal click event work only when window load But you load dynamic document then use 'on' binding or document binding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.