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].
Related
I tried to receive the data from a form to another using the following code it worked.
var fname = document.getElementsByName("fname")[0];
fname.value = getUrlVars()["fname"];
Now i want to receive the data from form to a table which is already created.
I used the code as
$("table").html("<tr><td>"+fname +"</td><td>"); its not working.
In this statement,
var fname = document.getElementsByName("fname");
fname.innerHTML = "fname";
What is the element with name "fname"?
If its a form element like textbox then it should be like,
var fname = document.getElementsByName("fname");
fname.value = "fname";
your code will only work if the element is not a form element like p or div, etc tags.
Edited Code:
I hope your second page is student.html and you have written the receiveData() in this page. Then you need to read the url and set the parameter value to the element. Like the one am writing below, provided your wrote the same name in form 2 as in form1,
var fname = document.getElementsByName("fname")[0];
fname.value = getUrlVars()["fname"];
2ndly yo can do this for textbox, but for the radio and dropdown you need to write som if-else statement.
Refer this http://papermashup.com/read-url-get-variables-withjavascript/
Hope you are getting what am willing to say.
Re-Edited Code:
Add this function with the receiveData() function.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Code for Radio Button,
var sex = document.getElementsByName("sex");
sexValue = getUrlVars()["sex"];
for(i=0;i<sex.length;i++)
{
if(sex[i].value==sexValue)
{
sex[i].checked=true;
break;
}
}
Two issues with the code.
This is a useless statement, you need to save the result to some variable (not to mention Nmae):
document.getElementsByNmae("lname")
Should be:
var lname = document.getElementsByName("lname");
And then (setinnerHTML -> innerHTML):
lname.innerHTML="lname";
Use docs not your own imagination:
var newEl = document.getElementById("newElDay");
newEl.innerHTML = document.getElementById("oldElDay").innerHTML;
Apart from other problems which people have mentioned, perhaps you are missing this as the last line of your Javascript code inside Receivedata() :
document.getElementById('myform').submit();
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
};
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.
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);
}
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).