Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery make enter button submit form

Tags:

jquery

I have a simple form that looks like this:

<form action="#" name="submit" method="post">
        <input name="zip" id="zip" type="text" value="" class="zip-start" />
        <div class="form-submit"><a href="" id="zipformSubmit" rel="zipformSubmit" class="zipformSubmit">Submit</a></div>
    </form>

I have JS that looks like this:

<script> 
    $(document).ready(function() { 
    $("a[rel=zipformSubmit]").click(function(e) { 
        e.preventDefault();
         var zip = $('#zip').val();
         if (zip.length < 5) { alert("Please enter a valid zip code"); return false;};
        $.colorbox({href: "/ppc/form.htm?zip=" + zip, iframe:true, innerWidth:800, innerHeight:600}); 
    }); 
    });  
</script>

The problem is that the user can only submit this form by clicking on the submit button. Any ideas on how i can adjust the js so that the enter button also submits the form?

thanks in advance

like image 738
rob melino Avatar asked Sep 23 '26 14:09

rob melino


1 Answers

Use as well jQuery's submit [docs] method to listen for an form submit from clicking enter.

<script> 
    function submitHandler(e) {
        e.preventDefault();
        var zip = $('#zip').val();
        if (zip.length < 5) { alert("Please enter a valid zip code"); return false;};
        $.colorbox({href: "/ppc/form.htm?zip=" + zip, iframe:true, innerWidth:800, innerHeight:600});
    }

    $(document).ready(function() { 
        $('form').submit(function(e) {
            submitHandler(e);
        });

        $("a[rel=zipformSubmit]").click(function(e) { 
            submitHandler(e);
        }); 
    });  
</script>

You should however change this $('form') to something more specific. Add an id for the form and it should be perfect.

like image 99
Rihards Avatar answered Sep 28 '26 00:09

Rihards



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!