Submit form JavaScript onChange

Auto Submit HTML Form

This tutorial example shows how to submit form automatically when a radio button is selected. The below example has two radio buttons and when one of them is selected then the form gets submitted automatically and displays the corresponding value.

Sometimes you may need to submit the form automatically. Based on form submission, you may need to do some further processing. You can submit form automatically using events, such as, onClick, onChange JavaScript events which can be applied on many tags like <select/>, input type radio, input type checkbox, etc.

Code Implementation

The following code is a combination of PHP, HTML and JavaScript that show how HTML form gets submitted automatically when a radio button is selected.

<?php
$radio = "";
if (isset($_GET["db"])) {
    $radio = $_GET["db"];
}

if ($radio == 'domestic') {
    echo 'domestic';
} else {
    echo 'awsome';
}
?>
<html>
    <head>
        <script>
            function autoSubmit()
            {
                var formObject = document.forms['dbForm'];
                formObject.submit();
            }
        </script>
    </head>
    <body>
        <form name='dbForm' id='dbForm'>
            <input type="radio" name="db" <?php if ($radio == 'domestic') { ?>checked='checked' <?php } ?>
                   value="domestic" onChange="autoSubmit();" />Domestic
            <input type="radio" name="db" <?php if ($radio == 'international') { ?>checked='checked'
                   <?php } ?> value="international" onChange="autoSubmit();" /> International    
        </form>
    </body>
</html>

Once a radio button with value domestic or international is selected, the form gets submitted. The corresponding value is also displayed.

Leave a Reply

Your email address will not be published.