2

I'm using Laravel with some jQuery for a webapplication. When I submit an empty form, I redirect back to the page with the old values filled in (form model binding), which all works as expected.

The problem is at the jQuery part. I have several sections which are not shown when the value of a radio group is 0 (unchecked), and showed when it changes to 1 (checked). This works fine when I fill in the page, but it bugs when I redirect back if I have a validation error in the form.

When I have a form error, and I get redirected back to the page with the old values filled in, and read the selected values of the radio groups, all the values are still 0. Why is the val() 0 even when the radio has a selected value of 1?

var r4 = $('input[name="configtype"]');
var s4 = $('#comprehensive');

initsec(r4, s4);

function initsec(radio, togglesection){

    console.log(radio.val());

    //When being redirected back to the page with the radio selected at the value '1',
    //console.log still shows 0

    if (radio.val() == 1)
        {
            togglesection.toggle();
        }
    }

edit

var r4 = $('input[name="configtype"]:checked'); can't work in this situation because I'm using the radio field also in other places in my code where I shouldn't only get the checked value but instead of the checked value, thus not duplicate as far as I know (because I've read the var r4 = $('input[name="configtype"]:checked'); a million times but that's not possible in my code)

Markinson
  • 2,077
  • 4
  • 28
  • 56
  • Possible duplicate of [How can I know which radio button is selected via jQuery?](http://stackoverflow.com/questions/596351/how-can-i-know-which-radio-button-is-selected-via-jquery) – Koshinae Apr 19 '16 at 07:47
  • @koshinae did an edit to explain why I can't use the given link (because I've read that exact but couldn't find the answer ;-) ) – Markinson Apr 19 '16 at 07:55

1 Answers1

1

radio is a set of all radio elements not just the checked one so calling .val() will return the value of the first element in the set.

You can use .filter() to select only the checked item

console.log(radio.filter(':checked').val());

or

var r4 = $('input[name="configtype"]:checked');
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • This worked! I was trying to avoid using the second option because I had to use a variable without `:checked` in it, exactly what I was looking for – Markinson Apr 19 '16 at 07:51