Search code examples
javascriptjqueryhtmlradio-buttondouble-submit-problem

Why am I submitting the form twice? jQuery submit() with radio button


I'm using jQuery to submit a form in an MVC app. I have a breakpoint inside the controller and I see it is being hit twice. What am I doing wrong?

Here is my jQuery

 (function ($) {

    $(document).ready(function () {

        $(':radio').change(function () {

            $('#frmMDR').submit();
        });

    });
})(jQuery);

and here is the form html

<form action="/Module/ModuleIndex" id="frmMDR" method="get">
  <input id="rdoMaintenance" name="module" type="radio" value="Maintenance" /><label for="rdoMaintenance">M</label>
   <input id="rdoDiagnostics" name="module" type="radio" value="Diagnostics" /><label for="rdoDiagnostics">D</label>
   <input id="rdoRepair" name="module" type="radio" value="Repair" /><label for="rdoRepair">R</label>
 <input id="hdnVehicle" name="hdnVehicle" type="hidden" value="" />
</form>

I'm guessing I shouldn't be using the change event. If anyone knows how to correct the problem, I'd love to hear any ideas. Thanks so much for any tips.

Cheers,
~ck in San Diego


Solution

  • You are getting two hits because two radio buttons are changing state. Radio buttons only allow one element in a group to be selected so when you are clicking a radio button, two events are happening:

    1. A new radio button is selected
    2. The previously selected radio button is deselected

    This is two events and the reason why your code is being hit twice. To solve it you could give your radio buttons a class and then handle the event on click using the class as the selector.

    <input class="radio" id="rdoMaintenance" name="module" type="radio" value="Maintenance" /><label for="rdoMaintenance">M</label>
    <input class="radio" id="rdoDiagnostics" name="module" type="radio" value="Diagnostics" /><label for="rdoDiagnostics">D</label>
    <input class="radio" id="rdoRepair" name="module" type="radio" value="Repair" /><label for="rdoRepair">R</label>
    

    And your jQuery could be:

    $('.radio').click(function () {
        $('#frmMDR').submit();
    });