0

iam new to javascript and currently iam trying to add values from form elements to an array, one will hold element value and second will hold description for that value, e.g

first array: form element.value = 50 second array: description num of years: form element = 50

output: years: 50;

i have a form with multiple elements(radio, textbox, checkbox etc) and each time the user select or click for answer this answer should be stored to an array.

here is what i tried:

i have created function which is called on click event button in this function i have a loop which runs trough all elements in a form (mainForm) and getting the values.

this is rough version of my code, as i have tried many ways and dont know which way should i take;

function Calculate()
{
var elements = document.getElementById('mainForm').elements;
    for(var i = 0; i < elements.length; i++)
    {

       outputValue +=   +=  elements[i].value;         
outputDescription += description[i];


    } 
    document.getElementById('lblValues').innerHTML = output ;
}

thing is that for radiobuttons iam getting all values not just the one that was checked and i think here i will need to create extra function?

now iam thinking if it is good way to iterate trough all elements using elem.length or rather iterate how much an array can hold data e.g array.length

here is where iam lost, playing with it it for few days and now iam lost. i would appreciate the help with in what approach should i take, shoud i create more functions for each element in a form and get those values and then store them in an array? thanks

1 Answers1

0

Try this link to get values for radio Get Radio Button Value with Javascript

In past I never iterated through elements, I have separate methods for each fields that I need to set or get. This gave me more power to control over my app. However, this could get troublesome if you have 100's of fields. if you do go through above method then you can store it in an object like

var elementList = [];
elementList.push({
                   value: somevalue, 
                   description: 'some description'
})
Community
  • 1
  • 1
sylar
  • 366
  • 2
  • 9