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
  • none of the radio input is checked – line88 Oct 24 '18 at 20:04
  • Don't repeat ids. Use a class, and use the class for your selector. https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page – Taplar Oct 24 '18 at 20:06
  • Yes but I'm the one that will checked it sir. For example I have checked the Male radio button ang submit but still I got the brackets return value from my console.log – jeloneedshelp Oct 24 '18 at 20:06
  • Also, only one of these element can be checked at a given time. They share the same name, so returning an array really doesn't make sense. – Taplar Oct 24 '18 at 20:09
  • Ohh I see. So what is your suggestion sir? – jeloneedshelp Oct 24 '18 at 20:10
  • No need to do the each. The selector will return 0 or 1 elements, and if it's 1, just use it – Taplar Oct 24 '18 at 20:10

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,336
  • 1
  • 9
  • 21