Javi Vera
Javi Vera

Reputation: 1

JavaScript function writing

This is what im doing:

1.

function getVal() {
    var asd = document.getElementById("nomyape").value
}
  1. getVal()

  2. asd (to check if the var has something)

  3. asd is undefined

pd: "nomyape" has a value , if i do document.getElementById("nomyape").value I get the value, thats why i know im pretty close

What i would like to make its a function that gets 6 diferents values from differents id, so when i call it i can gather all the form data

Thank you in advance

Upvotes: 0

Views: 213

Answers (3)

Troy
Troy

Reputation: 1839

You should return the value from your function and assign it to a variable.

function getVal (elementId) {
   return document.getElementById(elementId).value;
}

var a = getVal("id_of_element1");
var b = getVal("id_of_element2");

In your version of the code you create a local variable in the function that is only visible in the function.

Assuming all of your element's have id attributes, you could pass the element id into the function to get the value of each input.

Upvotes: 0

LostInCyberSpace
LostInCyberSpace

Reputation: 423

var values=[];
var ids=['nomyape_!','nomyape_2',...];
function getVals(){
  for(i in ids){
    values.push(
      document.getElementById(ids[i]).value
    );
  }
}

use a for loop to store all values in the values array.

Upvotes: 1

abs
abs

Reputation: 801

you can do like this. You need to remove var inside function which is making it a local variable.

var asd;
function getVal (){
 asd=document.getElementById("nomyape").value
}

Upvotes: 0

Related Questions