Sending form just by clicking on the radio button

Asked

Viewed 488 times

2

My question is the following: Observe the following form fields:

input type="radio" name="pagto" value="A"
input type="radio" name="pagto" value="B"
input type="radio" name="pagto" value="C"
input type="radio" name="pagto" value="D"

Note that the "name" is the same and the variable is in "value", according to the default.

What I need: When you click on a radio, the form is sent. I don’t want to use the "Submit" button, I want the submission to be at the time of the radio click and ALL fields of the form to be sent.

  • I know that’s not your question (and that’s why I’m just commenting), but I would say that sending the form by clicking on Radio Button is a bad idea. I don’t know the details of the system you are building, but this component allows the user to make a choice that can sometimes be sufficiently important (example: what freight option to pay?) to be allowed to think about and even change the initial choice. [...]

  • [...] Moreover, traditionally this immediate submission is not the default behavior, and certainly will not be expected by most users (especially if they are newcomers to your system). Thus, you can cause more problems than facilities. I suggest not to do this, or at least evaluate this option with some users before putting it into production.

1 answer

3

You need to add an event receiver change. I would also find click but change is more correct semantically and then you do form.submit() when this event is detected.

An example would be like this:

var radios = document.querySelectorAll('input[type="radio"]');
[].forEach.call(radios, function (radio) {
    radio.addEventListener('change', function () {
        document.querySelector('form').submit();
    });
});

jsFiddle: http://jsfiddle.net/0gkhygqx/

If you already know what the element is form you can do how the @ctgPi suggested, otherwise you can use this (http://jsfiddle.net/0gkhygqx/1/) looking for the element form to which this input belonging.

// isto fica dentro do event handler
var form = (function (el) {
    while (el.tagName.toLowerCase() != 'form') el = el.parentNode;
    return el;
})(e.target);
form.submit();
  • 1

    +1, but wouldn’t it be better to do something like var form = document.querySelector('form');, var radios = form.querySelectorAll('input[type="radio"]'); and form.submit();? This makes it easier to fix on the day that @Washington has more than one form on their page.

  • 1

    @ctgPi you’re right, I put together this idea and another variant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.