0

I need to trigger 2 events in same one but from different HTML elements. What I mean is that I have search text box and a search button. I need to display search results on keyup inside the search text box OR when the search button is clicked.

I found this answer on stack overflow but it is meant to be used by just one element and several events:

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

Is it possible or should I duplicate my script but change the event for each element ?

What I am using is:

$('#searchBtn').on('click',function() 
{ 
    surfData(); 
});

$('#searchTxt').on('keypress',function() 
{ 
    surfData(); 
});
4
  • Please include all relevant code. Commented Jun 30, 2017 at 11:14
  • Give me just 10 minutes I am testing something and I will post all the script for you guys Commented Jun 30, 2017 at 11:15
  • Just define a new class and assign it to both elements. Use that element for event delegation and you're done. Commented Jun 30, 2017 at 11:16
  • 1
    @hallleron didn't get what you mean, please look at my current script that I will add in a minutes and if I can use different thing Commented Jun 30, 2017 at 11:16

2 Answers 2

1

You can use this but it will have the side effect of triggering the callback (and your surfData function) when the searchBtn element registers a key press event as well as when the searchTxt element is clicked on (the latter being a very common way a user selects a text box). I believe @hallleron's will have the same problem.

$('#searchBtn, #searchTxt').on('click keypress',function() 
{ 
    surfData(); 
});

To avoid those side effects you'd need to leave the code you have (which is extremely simplified already; below is the only simplier version I could think of)

$('#searchBtn').click(surfData);
$('#searchTxt').keypress(surfData);
Sign up to request clarification or add additional context in comments.

Comments

1

This is what I meant with "define a class for them":

$('.search_elem').on('keyup click', function(){
  console.log("Event fired!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="search_elem" type="text" placeholder="search ...">
<button class="search_elem">Start search</button>

Comments

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.