user1290426
user1290426

Reputation: 153

Set cookies for form elements

I'm trying to take values from a from and then and when it is submitted turn the values into a cookies. This is what I have, but I wanted to know if there was a way to make it so I didn't have to keep writing out the same thing for all of the variables.

function submitValues(){

var firstName = document.forms["frm1"]["first_name"].value;
var lastName  = document.forms["frm1"]["last_name"].value;
var number    = document.forms["frm1"]["phNum"].value;

setCookie("firstName",firstName,365);
setCookie("lastName",lastName,365);
setCookie("number",number,365);
}

Upvotes: 0

Views: 2795

Answers (2)

Phrogz
Phrogz

Reputation: 303136

If you want to set cookies for all form elements, use the DOM2 form.elements collection:

var els = document.forms.frm1.elements;
for (var i=els.length;i--;){
  setCookie(els[i].name, els[i].value, 365);
}

If you want only specific, then write your code like so:

var els = document.forms.frm1.elements;
var cookiesToSet = ['first_name','last_name','phNum'];
for (var i=cookiesToSet.length;i--;){
  var name = cookiesToSet[i];
  setCookie(name, els[name].value, 365);
}

In the above, els[name] is equivalent to document.forms.frm1.elements[name].

In general, every property of every object in JavaScript is accessible via either "dot notation" (foo.bar) or "bracket notation" (foo["bar"]). You must use the latter when the property name is not a valid identifier(foo["names[]"] or foo["12 freakin' whales!"]) or when constructing the property name from a variable (foo[name] or foo["item"+i]).

Upvotes: 2

Ashley Strout
Ashley Strout

Reputation: 6258

You could shorten it somewhat by saving a reference to the form in a variable, like so:

var form = document.forms["frm1"];

var firstName = form["first_name"].value;
//...and so on

Or to shorten it even more by looping through all the <input> elements in the form:

var formInputs = document.forms["frm1"].getElementsByTagName("input");
for (var i=0;i<formInputs.length;i++) {
    setCookie(formInputs[i].name, formInputs[i].value, 365);
}

Upvotes: 2

Related Questions