jqueryformsselectsubmit

How to Submit Form on Select Change


I have the following form. I'd like it to be submitted automatically via jQuery when the user makes a selection, without needing to press the submit button. How do I do this?

<form action="" method="post">
    <select name="id" id="cars">
        <option value="">Choose</option>
        <option value="1">Toyota</option>
        <option value="2">Nissan</option>
        <option value="3">Dodge</option>
    </select> 
    <input type="submit" name="submit" value="Submit">
</form>

adeneo, I tried your suggestion but it's still not working. Here's the complete code, anything wrong?

<!doctype html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#cars').on('change', function() {
                this.form.submit();
            });
        });
        </script>
    </head>
    <body>
        <form action="" method="post">
            <select name="id" id="cars">
                <option value="">Select...</option>
                <option value="1">Toyota</option>
                <option value="2">Nissan</option>
                <option value="3">Dodge</option>
            </select> 
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>

Solution

  • Your form is missing an action value, which prevents submitting the form at the end. But in the mid-time you should correct this code:

    $(document).ready(function() {
      $('#cars').on('change', function() {
         document.forms[myFormName].submit();
      });
    });
    

    You can also submit a form by triggering submit button click event:

    $(document).ready(function() {
      $('#cars').on('change', function() {
        var $form = $(this).closest('form');
        $form.find('input[type=submit]').click();
      });
    });