Java script object data for functions - javascript

How do I acces some object data in a javascript function? All I want to do is to take some input from the html file and then if the input text is === to one of my objects in javascript i want to acces some data from that object to use within my function.
For example:
I have the html form with 2 text inputs and a button to acces the function. And in the javascript document I have two objecst called bob and susan with the data "bob.age = 25" and "susan.age = 30". So I want a function that calculates bob.age + susan.age. But I want to use the inputs of bob and susan in my form html. So when i have the inputs bob and susan i want the function to do bob.age + susan.age
here is my html form:
<form name="mmForm">
<label for="element1">E1</label>
<input type="text" id="element1">
<label for="element2">E2</label>
<input type="text" id="element2">
<input type="button" value="Calculate" onclick="procesForm_mm()">
<div id="resultfield_mm">Result:</div>
</form>
here my javascript function:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;
var e2 = document.mmForm.element2.value;
result_mm = parseInt(e1) + parseInt(e2);
document.getElementById("resultfield_mm").innerHTML += result_mm;
}
and this is the data i want to acces:
var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = "VIIIB";
Fe.perioada = 4;

Try this (a lot of guessing involved):
function procesForm_mm() {
var e1 = document.mmForm.element1.value;
var e2 = document.mmForm.element2.value;
result_mm = parseInt(eval(e1).A) + parseInt(eval(e2).A);
document.getElementById("resultfield_mm").innerHTML += result_mm;
}
var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = "VIIIB";
Fe.perioada = 4;
var Co = new Object();
Co.denumire = "Cobalt";
Co.A = 59;
Co.Z = 27;
Co.grupa = "IXB";
Fe.perioada = 4;
See it working here: http://jsfiddle.net/KJdMQ/.
It's important to keep in mind that use of the JS eval function has some disadvantages: https://stackoverflow.com/a/86580/674700.
A better approach would be to keep your JS objects in an array and avoid the use of the eval function:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;
var e2 = document.mmForm.element2.value;
result_mm = parseInt(tabelPeriodic[e1].A) + parseInt(tabelPeriodic[e2].A);
document.getElementById("resultfield_mm").innerHTML += result_mm;
}
var tabelPeriodic = [];
tabelPeriodic["Fe"] = new Object();
tabelPeriodic["Co"] = new Object();
var el = tabelPeriodic["Fe"];
el.denumire = "Fier";
el.A = 56;
el.Z = 26;
el.grupa = "VIIIB";
el.perioada = 4;
el = tabelPeriodic["Co"];
el.denumire = "Cobalt";
el.A = 59;
el.Z = 27;
el.grupa = "IXB";
el.perioada = 4;
(See it working here)
Note: This looks like a chemistry application, I assumed that the form is supposed to add some chemical property values for the chemical elements (i.e. A possibly being the standard atomic weight). The form would take as input the names of the JS objects (Fe and Co).

Related

Reading values from input fields created in an array with document.createElement()

I'm trying to build a table that the user can hit "new line" to create a new row of the table. I do this by foo.push(document.createElement("INPUT"));
function newLine() {
sArr.push(document.createElement("INPUT"));
sArr[sArr.length-1].setAttribute("type", "text");
document.body.appendChild(sArr[sArr.length-1]);
gArr.push(document.createElement("INPUT"));
gArr[gArr.length-1].setAttribute("type", "text");
document.body.appendChild(gArr[gArr.length-1]);
tArr.push(document.createElement("INPUT"));
tArr[tArr.length-1].setAttribute("type", "text");
document.body.appendChild(tArr[tArr.length-1]);
//alert(sArr.length+", "+gArr.length+", "+tArr.length);
var x = document.createElement("br");
document.body.appendChild(x);
}
function calc(){
var temp = 0;
var total = 0;
for(i = 0; i<sArr.length; i++){
total = total + calc2(i);
}
var o = document.getElementById("output");
o.value = total;
}
function calc2(i){
alert(i);
var s = document.getElementById(sArr[i]);
var g = document.getElementById(gArr[i]);
var t = document.getElementById(tArr[i]);
var VO2walkmin = 3.28;
var VO2rest = 3.05;
var C1 = 0.32;
var C2 = 0.19;
var C3 = 2.66;
var Cdecline = 0.73;
var s2 = s.value;
var g2 = g.value;
var t2 = t.value;
var negGrade = g.value;
if(g2 < 0){g2 = 0};
VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*(s2^2)));
VO2inc = VO2rest+(t2*VO2move);
VO2dec = VO2rest+(Cdecline*(t2*VO2move))
//var o = document.getElementById("output");
return VO2inc;
}
When run, I get the error:
Uncaught TypeError: Cannot read property 'value' of null
from line 66. Specifically, this line:
var s2 = s.value;
I'm struggling to find my mistake here... and all help is appreciated.
You create a new element, but it has no ID. And so you can't fetch it by ID. The result of document.getElementById(sArr[i]) will be null.
Check this answer to see how ID can be assigned to a newly created element:
Create element with ID
There's no need to use document.getElementById. sArr[i] is the input element itself, not its ID, so you can just read its value directly.
var s = sArr[i];
var g = gArr[i];
var t = tArr[i];

Form value always read as undefined in Javascript

I'm a new self taught programmer working on my first homework assignment, so I apologize if my naming convention is off. This is the most bizarre thing. No matter how I request the input value, (hoping to pull a number) it always reads as undefined.
Everything works in my javascript function except pulling the input value. I have used forms in the past, and the variables appear to be referencing it fine; I have tried both document.formName.inputName.value, as well as document.getElementById ('input-id').value and it returns undefined. I have renamed my form and variables so many times to see if that was the issue and stI'll nothing. I have tried both input type text and number, and stI'll undefined.
Am I missing something due to how new I am? Please help. Links to github and jsfiddle below.
https://github.com/MissElle/calculator?files=1
https://jsfiddle.net/MissElle/qf7xL8gj/
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff', '#ffbfbf', '#ffd299', '#ffffff', '#000000'];
function calcData(element) {
if(typeof element === 'number') {
console.log(element);
subCount.push(element);
var starDiv = document.createElement('div');
starDiv.className = 'star';
var starHolder = document.getElementById('star-holder');
starHolder.appendChild(starDiv);
starDiv.style.background = 'radial-gradient(circle, ' + starColors[Math.floor(Math.random() * starColors.length)] + ', transparent, transparent)';
numCount.innerHTML = subCount.length;
for(var i in subCount) {
subSum += subCount[i];
numSum.innerHTML = subSum;
var subMean = subSum/subCount.length;
numMean.innerHTML = subMean;
}
}else {
numCount.innerHTML = 'Not a Number';
console.log(element);
}
subSum = 0;
event.preventDefault();
}
function clearData() {
subCount = [];
subSum = 0;
subMean = 0;
numSum.innerHTML = '';
numMean.innerHTML = '';
numCount.innerHTML = '';
var starHolder = document.getElementById('star-holder');
var starDiv = starHolder.getElementsByClassName('star');
while(starDiv.length > 0) {
starHolder.removeChild(starDiv[0]);
}
}
<form name="compute" onsubmit="calcData()" onReset="clearData()">
<p class="bold">Please enter a number</p>
<input type="number" name="calculate" id="calculation" step="any"><br>
<input type="submit" name="submit" value="star">
<input type="reset" value="nostar" name="clearForm">
<div class="row">
<div class="typevalue"><h4>Count:</h4><h4>Sum:</h4><h4>Mean:</h4></div>
<div class="numbervalue"><p id="count"></p><p id="sum"></p><p id="mean"></p></div>
</div>
</form>
Move your variable declarations inside your function like this:
function calcData(element) {
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff',
'#ffbfbf', '#ffd299', '#ffffff', '#000000'];
...
If you declare your dataInput outside the function you get no value because that JS code is run after the page loads (before your user types any number in your function).
You have to declare it inside your function that way you get the value of your input when the user clicks on the button.

Accessing Excel's Object Model from Javascript

I have excel as an activeX object in javascript. I seem to be missing something with reards to how to interact with the object model from there. My watch window shows the value of the "Value" property of the range I am trying to pull data from as "undefined" when I try to assign "range.Value" to an array.
Unfortunately I am unable to update the outdated browsers on my machine at work so I cannot upload pictures.
My script:
function open_files(A, B, C)
{
var excel = new ActiveXObject("Excel.Application");
excel.Visible=true;
excel.DisplayAlerts = false;
var wbA = excel.Workbooks.Open(document.getElementById(A).value);
var wbB = excel.Workbooks.Open(document.getElementById(B).value);
var wbC = excel.Workbooks.Open(document.getElementById(C).value);
excel.EnableEvents = false;
excel.ScreenUpdating = false;
excel.Calculation = -4135 //xlCalculationManual enumeration;
var wb_collection = [wbA, wbB, wbC];
excel.Application.Run("'" + wbA.name + "'" + '!update_links');
var CLIN_list = [wbA.Sheets("Control Form").Range("B62:B141").value(1)]
for (i = 0; i = CLIN_list.length; i++)
{
if (CLIN_list(i) > 0)
{
var CLIN_list_count = i
}
}
var decrement_range_start = wbA.Sheets("Fee & Decrement Table").Range("AJ14")
//for (i = 0; i < 80; i++){
//Sheets("Fee & Decrement Table").Cells(decrement_range_start.column+i
// Model Setup for VBA
wbA.Sheets("CONTROL FORM").Activate
wbA.Sheets("CONTROL FORM").OLEObjects("TextBox21").Object.Text = wbB.fullname
wbA.Sheets("CONTROL FORM").OLEObjects("TextBox22").Object.Text = wbC.fullname
excel.Application.Run("'" + wbA.name + "'" + '!Run_JPO');
I found an answer on another forum. A Range cannot be assigned directly to a js array, it has to be converted. The line below works to fill my CLIN_list variable.
var CLIN_list = new VBArray(wbA.Sheets("Control Form").Range("B62:B141").value).toArray();

JavaScript, advanced .replace()

function changeText(getString){
var smiles_from_to = new Array();
smiles_from_to[":)"] = "ab"; smiles_from_to[":-)"] = "ab";
smiles_from_to[":("] = "ac"; smiles_from_to[":-("] = "ac";
smiles_from_to["B)"] = "af"; smiles_from_to["B-)"] = "af";
smiles_from_to[";("] = "crygirl2"; smiles_from_to[";-("] = "crygirl2";
smiles_from_to[":-*"] = "aw"; smiles_from_to[":*"] = "aw";
smiles_from_to[":D"] = "ag"; smiles_from_to[":-D"] = "ag";
smiles_from_to["(devil)"] = "aq"; smiles_from_to["(wtf)"] = "ai";
smiles_from_to["(sos)"] = "bc"; smiles_from_to["(boom)"] = "bb";
smiles_from_to["(rofl)"] = "bj"; smiles_from_to["xD"] = "bj";
smiles_from_to["(music)"] = "ar"; smiles_from_to["(angel)"] = "aa";
smiles_from_to["(beer)"] = "az"; smiles_from_to["(omg)"] = "bu";
smiles_from_to["(dance)"] = "bo"; smiles_from_to["(idiot)"] = "bm";
smiles_from_to["(clap)"] = "bi"; smiles_from_to["(gotkiss)"] = "as";
var replaced = getString;
for(var key in smiles_from_to){
replaced = replaced.replace(key, "<img src='"+chrome.extension.getURL("images/"+smiles_from_to[key]+".gif")+"' />");
}
return replaced;
}
Hi everyone ,I need to optimize code for something more simple, so try to avoid for loop..
"var replaced" is a huge html code (content of div that contains 100 lines of messages with date, username, userinfo(tooltip), message,.....)
This code is a piece from my chrome extension. so i cant do it php side.
You can use a single giant regex, of the form /:\)|:\(|.../g, then pass a callbacka as the replacement that looks up the match in your lookup object.

JavaScript - need help combining two scripts.

I’m trying to call a user input array.
I’m very new on Javascript but know I somehow need to reference the array (it is somewhere where I put the ???).
<script>
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var planetIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[planetIndex][0]=val1;
planetIndex++;
document.getElementById('name').value = ''; };
function worldChange() {
var newplanet = ????????????
var whichWorld = Math.floor(Math.random()*newplanet.length);
return planetIndex[whichWorld];
var planets = document.getElementsByClassName("world-name")
for (var i=0; i < planets.length; i++) {
planets[i].innerHTML = worldChange();};
};
</script>
<body>
<div>
<form>
<input type="integer" id="name"/>
<input type="button" value="Add Planets" onclick="insert (this.form.name.value);"/>
</form>
<input type="button" value="See planet!" onClick="worldChange()" />
<br> Hello <span class="world-name">Earth!</span><br />
</div>
</body>
I got both elements of the script to work perfectly on my site so every time someone hits a button it changes the guy in the story. But as you see if pulls from the array I created. I want to pull from an array that a user creates so they could input their own list of names.
so this script works fine:
function newGuy() {
var guys = new Array ("Jeff", "Mike", "George", "Harold");
var whichGuy = Math.floor(Math.random()*guys.length);
return guys[whichGuy];}
var guy = document.getElementsByClassName("guy")
for (var i=0; i < guy.length; i++) {
guy[i].innerHTML = newGuy();}
And this script works alone:
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var guyIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[guyIndex][0]=val1;
guyIndex++;
document.getElementById('name').value = ''; };
Just baffled on how to put them together.
There are a lot of problems with your script but to give you an idea on how to get it to work :
var planets = [];
// define how many planets there will be initially
var initialLength = 5;
// add the initital planets
for (x = 0; x < initialLength; x++) {
planets.push("planet" + x);
}
function insert() {
var planetToInsert = document.getElementById('name').value;
if (planetToInsert) {
// add the input to the array of planets
planets.push(planetToInsert);
document.getElementById('name').value = '';
} else {
alert("please enter a value");
}
}
function worldChange() {
// randomly pick an index
var whichWorld = Math.floor(Math.random() * planets.length);
document.getElementById('world-name').innerHTML = planets[whichWorld];
}
working sample here
For finding problems in you code jsFiddle can be of excellent help. Run JSlint to find the basic errors, put in alerts as poor mans debugging.
For a good javascript book I would recommend javascript patterns

Categories

Resources