Ashish
Ashish

Reputation: 769

Using jQuery to trigger Enter event

I have an image tag :

         <img src='Presale.png' alt='presell' onclick="presell()"/> Presell

Function :

function presell()
{
    $(".form-control").val("presell");
    var e = jQuery.Event("keypress");
    e.which = 13;
    e.keyCode = 13;
    $(".form-control").trigger(e);
}

What I wanted to do was to fill a search box with some text and trigger enter the moment a particular image is clicked so that search related to that image is made. But this code is putting the value to the search box but not triggering enter.

Upvotes: 0

Views: 729

Answers (3)

Playmaker
Playmaker

Reputation: 1456

I assume what you need is to simulate a 'return/enter' key press which would most naturally submit the value of the input (which can be via submit/AJAX)

.trigger() would call the eventhandler and not simulate the native browser event. Refer: http://learn.jquery.com/events/triggering-event-handlers/

You would then need to bind an event handler to the enter keypress and provide what is to be done anyway. Which means including .submit() or post() or $.ajax() or whatever code that is called (unless it is defined on a trigger handler)

What you probably need is .simulate(); available via jquery.simulate.js

Upvotes: 0

James Hibbard
James Hibbard

Reputation: 17795

You can do it like this:

<img src='Presale.png' alt='presell' /> Presell
<form>
    <input type="text" class="form-control" />
</form>

Note: I removed the click handler from the image.

And in the JS:

$("img").on("click", function(){
    $(".form-control").val("presell");
    $("form").submit();
});

Demo

Upvotes: 1

Vince
Vince

Reputation: 381

You need to submit the actual form, instead of triggering a keypress event with enter's keycode (does not work)

e.g.

$("form").submit();

Upvotes: 1

Related Questions