Set cookies for form elements - javascript

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);
}

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]).

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);
}

Related

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

dynamic object properties javascript

Having issues with this code block:
var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');
name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);
If I take out the .val on both lines, the code works. I'm trying to dynamically create the "
nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.
Thanks for any help
When trying to assign
nutrients[name].val = tds[1].innerHTML;
the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use
nutrients[name] = {
val: tds[1].innerHTML
};

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

How to store a div ID value globally

I am creating an application that uses the same number pad to fill out two separate text style form values using javascript.
I found out how to gather a div ID for use inside of a function (for say toggling the hide value), but I need to save this value somehow so that I can know which field to put the numbers into when they come in.
I tried using a global variable for this, but it does not seem to work as the ID does not seem to be recorded as a String value.
The code that I am using does toggle the show/hide attribute, but if I use an alert box to pop what the variable I am using as storage is it reads [object HTMLDivElement]
My script looks like this (bear in mind that I am a noob to javascript).
<script type="text/javascript">
<!--
keypad.display="none";
//Classes for the numberpad on the text fields.
var padName = ""; //Storage for the name of the current pad.
function numPad(field) {
var pad = document.getElementById("keypad"); //manipulating pad.
var ref = document.getElementById(field);//gather the field info.
if (pad.style.display == "block") { //Open or close?
pad.style.display = "none"; //Blank out.
padName = "";
}
else {
pad.style.display = "block";//Set to refer to correct field.
padname = ref;
alert (ref);
}
}
function click(id) {
var key = document.getElementById(id);
var total = padName.value();
if (key == "Backspace") total.slice(0, -1);
else if (key == "Enter") numPad("blanck");
else total += key;
padName.value = total;
}
-->
</script>
// to get the ID by direct property access of the DOM element
var ref = document.getElementById(field).id;
and then ref stores the ID value.
I would suggest:
// create an object to store app-wide settings
// access properties like this: appSettings.propertyName
var appSettings = { padName: "" };
...
var ref = document.getElementById(field).id;
appSettings.padName = ref;
to avoid polluting the global namespace.
To get/set the value of the pad, you'll need to do this:
// to get
var total = document.getElementById(appSettings.padName).value;
// to set
document.getElementById(appSettings.padName).value = "something";
You should read up on DOM objects and properties.
For starters, ref is assigned a reference to a DOM element. You are then assigning this reference to padName, hence the [object HTMLDivElement] alert.
If you just want the ID stored in padName, use
padName = field;
Also, you're mixing cases of padName. You have both padName and padname.
Further, as mentioned in the comments, use the console for debugging. It's much more comprehensive than an alert.
I can't tell what's happening in your click function. You seem to be expecting padName to be an object of some kind however where the value() method and value property comes from is anyone's guess (FYI only form elements have value properties).

in javascript do, what is correct way to get FORM name?

in a form, form.name will usually return the form's name, but will not if the form has an element named "name"
var f = document.createElement('form');
f.hasAttribute('name'); // false
f.name = 'abc';
f.getAttribute('name'); // "abc"
var i = document.createElement('input');
i.name = 'name';
f.appendChild(i);
f.name; // HTMLInputItem
f.getAttribute('name') // "abc"
f.name = 'efg';
f.name; // HTMLInputItem
f.getAttribute('name') // "efg"
from this exercise, it seems that a FORM's name property is really its attribute.
this behavior is drastically different from value
var i1 = document.createElement('input');
var i2 = document.createElement('input');
// test value
i1.setAttribute('value','value1');
i1.getAttribute('value'); // value1
i1.value = 'value2';
i1.getAttribute('value'); // value1
i2.value = 'value1';
i2.hasAttribute('value') // false
// test name
i.setAttribute('name','name1');
i.getAttribute('name'); // name1
i.name = 'name2';
i.getAttribute('name'); // name2
i2.name = 'name1';
i2.hasAttribute('name') // true
value uses its attribute as a default, whereas form.name is a method that first tries elements having element.name='name' and then uses the attribute('name')
There is confusion about when and how to access those kind of "special propertys" from a DOMElement object. Like .name, .value, .tabIndex, etc. The direct object access comes from the old days and works just fine in all major browsers. So basically there is nothing wrong by calling
form.name
But as you mentioned, there might be some trouble if there are named child nodes. The W3C recommends to always use the .setAttribute() / .getAttribute() methods. In this particular instance its probably the best advice to give. On other occasions I'd still go with the direct access since it's just so much less to write and also convinient to me.
If you wants to get the form name
var names[] =
document.getElementsByTagName('form').getAttribute('name');
(or)
var name = document.getElementById('form_id').getAttribute('name');

Categories

Resources