0

Hi I have this variable in jquery that gets the value of checked input radio button,

var gender = [];
    $("input[type='radio'][name='gender\\[$counter\\]']:checked").each(function ()
    {
        gender.push($(this).val());
    });       

    console.log(gender);

My input field looks like this,

<input id="gender" value="Male" name="gender[$counter]" type="radio" />
<input id="gender" value="Female" name="gender[$counter]" type="radio" />

But the console.log(gender); returns the value "[ ]" but not the value of that input field. What seems to be the problem? Please help.

jeloneedshelp
  • 143
  • 2
  • 11

1 Answers1

1

Because you defined gender as an array []... therefore it is showing gender as an array [].

Why is gender an array? Gender is either none, male, or female.... not more than one. So start with

var gender = "";

Then no need to loop through the elements because only one will be checked. And just to be sure and avoid exceptions first check if a radio is checked or not:

if($("input[type='radio'][name='gender\\[$counter\\]']:checked").length > 0){    
   gender = $("input[type='radio'][name='gender\\[$counter\\]']:checked").val();
}
Nawed Khan
  • 4,393
  • 1
  • 10
  • 22