Search code examples
jqueryformssubmitmultiple-forms

jQuery - submit on return for one form disabling submit on return for another form


I have a page with more than one form. One form (see below example) has an input to add rows to a table on the page. Each of the rows in the table can be selected (checkbox) on/off. The other form submits the page sending which rows were "on" to the next page.

So, the initial problem was that people were entering a url and clicking return to add it to the table, but instead is was not adding it, but submitting the 'other' form (mainForm).

So, I added the jQuery below. That fixed the problem -- now, when the url field is in focus and you click return it adds a url to the list and does not submit the mainForm.

However, when that field is NOT in focus, pressing return does nothing - when I expected it to submit the form (the default behavior) ... since the event is only attached to that one input field.

HTML (greatly simplified):

<form name="data>
 <input id="url" class="field" type="text" size="65" name="urlText">
 <input class="hubField" type="button" value="Add Url" name="urlAddButton">
 <table>
    <tr>
       <td><input type="checkbox"></td>
       <td>Description text</td>
       ....and so on...
 </table>
</form>

<form name="mainForm">
 <input type="SUBMIT" value="Load Selected Urls" name="Submit">
</form>

JS/jQuery:

$(document).ready(function() {
    $('#url').bind('keyup',function(e) {
        if (e.which == 13) {
        $('input[name="urlAddButton"]').focus().click();
        e.preventDefault();
        }
    })
});

I'm fairly new to jQuery, so be nice. ;-) In js I'd probably just write something saying if that field is not in focus and return is pressed, submit main form. Is there a trick to do this easier in JQuery?


Solution

  • If I understand, you want to submit the mainForm when a user press enter while he's not in the "url" input. When he's in, you trigger the click on "urlAddButton". If so, here is a working example on jsFiddle : http://jsfiddle.net/MUUUE/

    $(document).ready(function(){
        $(this).bind('keydown',function(e) {//keyDOWN (for the input)
            if(e.which == 13) {//if enter is pressed
                if(e.target.id == "url"){//and we're in the url input
                     $('input[name="urlAddButton"]').focus().click();
                     e.preventDefault();
                }
                else if(e.target.type != "textarea" && e.target.type != "text"){//else, we submit the main form (if we're not in another input or textarea)
                    $("#mainForm").submit();//id attr added in the html code
                }
            }
        })
    });
    

    But, in the end, I'm not sure that it's so good to submit a form while you're not in an input.