0

I am trying to modify a jQuery that fires an event when either: a) the search text input field is clicked, or b) the search button is clicked

How do I change the code below to instead fire an event when a normal button class is clicked?

$( 'form[role=search] input, form[role=search] button' ).on( 'focus, click', function( event ) {

My button class is ".search-toggle", and I've tried replacing the above code with: $(".search-toggle").click(function( event ) { but that didn't work.

Here is a rough snippet of the kind of button I'm trying to target.

.search-toggle {
  background-color: #028A0F;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}
<!DOCTYPE html>
<html>
<head>
  
</head>  
<body>
<ul>
  <li style="float:right">
  <button type="button" class="search-toggle">Search</button>
  </li>
</ul>

</body>
</html>
Cobo
  • 7
  • 2
  • Can you create a snippet with the HTML for that section so we can see what elements you are targeting? – Andrew Halpern May 24 '20 at 05:02
  • Updated with a rough snippet for reference. – Cobo May 24 '20 at 05:09
  • You can use `change`, but `change` will be called after losing focus. Please check this answer if you wanna fancy input https://stackoverflow.com/questions/17317465/jquery-textbox-change-event-doesnt-fire-until-textbox-loses-focus – MarshalSHI May 24 '20 at 05:22
  • It's confusing and not clear .. By `form[role=search] input` and `form[role=search] button` this means you've a form with input and button inside of it .. and in your snippet there is no form tags.. So what you want?? .. You want the `search-toggle` to just trigger the input `focus` and the `button` click for your not-posted form .. or you've a new html structure with new input and new button without a form and want to make the `search-toggle` control that?? or ...? – Mohamed-Yousef May 24 '20 at 06:05
  • I am not using a form. I need to adjust that line of code to accept a click on my button class "search-toggle" instead to trigger the event. – Cobo May 24 '20 at 07:16

1 Answers1

0

It should works, but have you included JQuery library? You're right with this code:

$(".search-toggle").click((e) => {
 // put here your code
});

However I suggest to add the attribute 'onClick' on button and then check that the function have been called, if not, check that the button it's clickable and no element it's going on it

Biagio Boi
  • 58
  • 6