简体   繁体   中英

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

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();
});

You should probably just check for selected within the change function for which is selected. This way it'll only fire for the selected radio button, and you don't need to worry about binding or unbinding any events, and it should work regardless of what input method changed it.

Here's an article on handling events from check boxes and radio buttons in JQuery .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM