tags:

views:

66

answers:

1

Hi,

I have a text box in my page which the user will type something to submit. However, I do not want to have a submit button but instead I want to listen for the Enter key press in order to submit.

The thing is, there will be couple of textboxes in this one page and I only want to submit the textbox that has just been typed into.

I know how to find out which key was pressed using jquery but I think in my scenario, I need to see if the cursor was inside a specific textbox. is this right? if so, how is this achieved using jquery? In general is my approach ok? or should I definitely have a submit button?

kem...

+1  A: 

Please be aware this is considered bad practice; not only are you going to restrict the submission only to people with JS enabled, people expect to have a submit button to their forms. It's how the web works. The proper way of doing this is to have a form for each of your textboxes.

That being said, if you had a set of text fields:

<input type='text' name='x1' class='onenter'>
<input type='text' name='x2' class='onenter'>
<input type='text' name='x3' class='onenter'>

You could do this with jQuery:

$(function() {
    $('input.onenter').keyup(function(e) {
        if(e.keyCode == 13) {
            // enter was pressed, do whatever
            // $(this) is the current textbox
        }
    });
});

"whatever" could be an asynchronous request or an actual form submission, depending on your needs.

Paolo Bergantino
thank you.. your answer both cleared my mind about my paradox and also you gave an example on how to do it.
Emin