views:

286

answers:

2

Hi,

I have an input box

<input type="text" name="search" id="search" />
<img src="icon.png" alt="" id="doSearch" />

I use Jquery and I have onclick event for "doSearch". So when I enter some words like "ab" .. and click on "icon" It sends an ajax request to php file and gets results back appended to dom.

  $('#doSearch').click(function() {
 $(".showResults").show("fast");
 var input_text = $('input[name="search"]').val(); //retrieve text
 $.ajax({
  method: "get" ...
  ... some more lines 
 }) etc etc

I am wondering how can I trigger onclick function automatically, when some characters are entered in the input box so that users dont have to click on image icon to get the results. Also, how I can set focus on the image icon when I press tab key while in the input box.

Thanks a lot for your help.

EDIT:

I have some other input boxes in the same form as well. So this input acts as somewhat similar to stack overflow tags input.

+2  A: 

Something like that?

$('#doSearch').keyPress(function(e){
  if($(this).val()=='??') $('#doSearch').trigger('click')
});
Thinker
Yes, I am looking for something like this. What does the "??" mean?? thanks
Wbdvlpr
It's your condition whenever send click or not. You can for example check if input value is longer than 2 letters.
Thinker
+2  A: 

The proper way to do it would be to do this:

<form id='search'>
<input type="text" name="search" id="search" />
<input type="image" src="icon.png" />    
</form>

That way the image will be the submit button of the form, and whenever a user presses enter the form's submit event will be fired and you can do what you want.

This is how you could do the jQuery:

$('#search').submit(function() {
    // do what you were doing
    return false; // prevent form submission
});

This will also have the upside of being friendly to people with Javascript disabled, as you could then check in the server if it is not an AJAX request and perhaps display the full page with the requested content instead. I am pretty sure this will also make it so that TAB goes to the image as well.

Paolo Bergantino
Actually, this not just the one search box in form .. the form has some other input boxes as well. This input box acts as somewhat similar to TAGS input when we create a new question. This is the first time I noticed using <input type="image"> .. thanks.
Wbdvlpr