Tim C
Tim C

Reputation: 5714

get all elements in form

Im learning Javascript as my application grow and am pretty much starting from scratch i.e im very new to javascript.

What Im trying to do

Get value of all selected radio buttons on form

Psuedo

  1. Get all elements in form assign to array
  2. Loop over elements if type is radio and is checked assign to array

My Code

var elmnts = document.getElementById("makePicksForm");
var lngth = document. getElementById("makePicksForm").elements.length;

for(var x = 0; x< lngth; x++);
var allElmts = elmnts.elements[x]
 if(allElmnts.type == "radio")
window.alert(allElmnts);    
}

My HTML

<form id="makePicksForm">
 <input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team1'].' "onclick="return disp()"><span>'.$team1.'</span>
     </label>
     <br />
   <br /> <label class="yellow">
   <input type="radio" id="picks'.$x.'"  name="picks['.$x.']" value="'.$row['team2'].' "onclick="return disp()"><span>'.$team2.'</span>
   </label><br />
   <br />
    <label class="pink">
    <input type="radio" name="picks'.$x.'" value="draw">
    <span>Draw</span>
    </label><br />';

My Problem

enter image description here

I would like to know what am I doing wrong, why is it that variable allElmnts is not defined, any suggestion how I can fix this?

Upvotes: 2

Views: 68

Answers (2)

Balachandran
Balachandran

Reputation: 9637

use map() in jquery

var allSelectedRadioValue = $("#makePicksForm [type=radio]:checked").map(function() {
    return this.value;
}).get();
console.log(allSelectedRadioValue)

Fiddle

Upvotes: 1

Adil
Adil

Reputation: 148120

Remove semi-colon after for loop signature as it will not execute statements under loop with loop. Also use code block for enclosing multiple statements under for loop.

for(var x = 0; x< lngth; x++)
{
    var allElmts = elmnts.elements[x]
    if(allElmnts.type == "radio")
         window.alert(allElmnts);    
}

Upvotes: 2

Related Questions