How do I acces javascript database from a html form? - javascript

I just want to acces a database in javascript from a form in the html file and pass it in a javascript function.
So what I realy want to do is take the value that I input in the html and use it in a function that takes some object data and do some simple math.
So the form i want to use looks like this:
<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>
And here is the javascript data i want to acces:
var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = VIIIB;
Fe.perioada = 4;
What I want to do is to acces the Fe.A = 56; from the Fe object while I have the inpun of "Fe" in the html file and then pass it in this function that seems to not work:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;
var e2 = document.mmForm.element2.value;
result_mm = e1.A + e2.A;
document.getElementById("resultfield_mm").innerHTML = result_mm;
}
I look for some methods to do this trick and help me get on my tracks my first project as a web developer :) so anyone who will help me i will be verry greatefull.

result_mm = e1.A + e2.A;
That part will give you a error since a value does not have properties, what you have to do is this:
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;
}
Link http://jsbin.com/ifeluf/1/edit

Related

JavaScript - Dynamically add table rows in HTML table

I have the following script by which I want to achieve to dynamically add rows in an HTML table on my website:
<script>
var globalIterationVariable = 0;
document.onload = $globalIterationVariable = 1;
$('document').ready(function() {
$('.add_another').click(function() {
var globalIterationVariable;
var newRowVariable = '<tr><td><center><input name="nazovPolozky';
newRowVariable.append(String($globalIterationVariable));
newRowVariable.append(' type="text"></center></td> <td><center><input name="pocetPolozky');
newRowVariable.append(String($globalIterationVariable));
newRowVariable.append('" type="number" step="1" min="1"></center></td> <td><center><input name="jednotkovaCenaPolozky');
newRowVariable.append(String($globalIterationVariable));
newRowVariable.append('" type="number" step="0.01" min="0.01"></center></td></tr>');
alert(String(newRowVariable));
$("#tbl").append(String(newRowVariable));
globalIterationVariable++
});
});
</script>
This script though gives me the following error:
Uncaught TypeError: newRowVariable.append is not a function
Can anybody, please, help me to get this script working?
Thank you.
P.S.: This script is launched once I press a specific button on my website which has a class='button add_another'
You should define newRowVariable as a DOM element ->
const newRowVariable = document.createElement('tr')
Then append the content (your string) to it ->
newRowVariable.innerHTML = `<td><center><input name="nazovPolozky ${$globalIterationVariable}" type="text"></center></td>
Notice I use `` and not '' or "", it's because you can use javascript variables inside a string like that ->
const text = "World"
const superString = `Hello ${text}`
// a console.log(superString) will return 'Hello World'
Jquery might be usefull when you are a complete begginner, but you'll figure out soon that it's way simpler to use pure javascript ;)
This is a string
var newRowVariable = '<tr><td><center><input name="nazovPolozky';
This is a jQuery object
var newRowVariable = $('<tr><td><center><input name="nazovPolozky');
This is how you append a string to a string
var newRowVariable = '<tr><td><center><input name="nazovPolozky';
newRowVariable += "/></td></tr>";

JS to perform calculation based on user input

I have a code where I am trying to calculate a total value based on the value of the input selected by a user. It seems simple but I can't get the total to reflect. Please can someone show me where the fault is?
function calculate() {
var panel = parseInt(document.getElementsById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
}
document.getElementsById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate">Result</button>
<p id="total_hours">result displays here</p>
You need to
use for onclick="calculate()" take the function call, not only the function,
use getElementById, spelling matter,
declare all variables,
and finally move the output inside of the function
function calculate() {
var panel = parseInt(document.getElementById("panel").value),
panelv = 65,
panelt = panel * panelv,
derating_value = 2,
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
getElementById is singular
declare your vars
call calculate() with brackets
assign the value inside the function
</input> is not needed
Here is a version with eventListeners since other answers already showed you how to fix YOUR version
function calculate() {
var panel = +document.getElementById("panel").value;
if (panel === "" || isNaN(panel)) panel = 0;
let panelv = 65;
let panelt = panel * panelv;
let derating_value = 2;
document.getElementById("total_hours").textContent = (panelt * derating_value);
}
window.addEventListener("load", function() {
document.getElementById("calc").addEventListener("click", calculate)
calculate(); // run at load
})
<input type="number" id="panel" placeholder="panel quantity"><br>
<button type="button" id="calc">Result</button> result displays here: <span id="total_hours"></span>
First, you should call method calculate.
<button type="button" onclick="calculate()">Result</button>
Then, add this line document.getElementsById("total_hours").innerHTML = total_hours_standby; inside calculate function.
Alos, typo error: document.getElementById instead of document.getElementsById
There are couple of issues here:
Most you could have found out if you had looked into console logs.
For starter the function is called getElementById not getElementsById, because there is supposed to be only one element with unique id, so plural does not make sense here.
Another one is a logic error: not updating content after clicking on button i.e when calculate gets executed.
There is also one more syntax error, which is how functions should be passed to HTML element's attribute. It needs to be functionName() instead of functionName
This is how simply fixing this code could look like:
var total_hours_standby = 0;
function calculate() {
var panel = parseInt(document.getElementById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
document.getElementById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
Here I give you couple of ideas for improving it.
Since you use global variable total_hours_standby it may be a good
idea to encapsulate it. So called module pattern should do the job.
New value of total_hours_standby does not seem to depend on an old
one, so I guess you mean to use it somewhere else - in order to do
so, you need to expose it with "public" getter.
If above is not the case, then you don't need total_hours_standby
variable at all and you can just directly return it or display it
without storing this value in variable.
I put code for rendering in separate function - this is because rule
of thumb for functions is that they should have single
responsibility. One functions for calculations, another for rendering
and then one function for handling user's input and click event, that
uses two previous ones. This way if for example you only want to
calculate something without rendering result, then you just, simply can :)
I also stored DOM nodes in variables, instead of calling
getElementById, it is not due to performance, how it is often
assumed, I did it only for better readability.
Constants instead of hard-coded values.
var Calculator = (function() {
const panelInput = document.getElementById("panel");
const output = document.getElementById("total_hours");
const PANEL_V = 65;
const DERATING_VALUE = 2;
const render = value => output.innerHTML = value;
const calculate = value => value * PANEL_V * DERATING_VALUE;
let total_hours_standby = 0;
return {
handleInput: function() {
total_hours_standby = calculate(panelInput.value);
render(total_hours_standby);
},
getTotalHoursStandby: () => total_hours_standby
};
})();
<input type="number" id="panel" placeholder="Panel quantity" />
<button type="button" onclick="Calculator.handleInput()">Calculate</button>
<p id="total_hours">Result displays here</p>
It is typo,
document.getElementsById
should be
document.getElementById

Set cookie to have a value of form entry

Asked a related question earlier, but it looks like it was lacking a context, so, couldn't make it work.
Trying to set a cookie value of a form entry on click (using carhartl jquery plugin). And getting nothing. Not even errors.
Cookies plugin is included into head portion of the page.
html of it
<input type="text" class="signfield emfield" />
<input type="text" class="signfield nam1field" />
<input type="text" class="signfield nam2field" />
<div class="submt sbmtfrm" style="cursor:pointer;">Step 2</div>
and jquery
$(document).ready(function(window, $){
var emailvar;
var name1var;
var name2var;
$(".sbmtfrm").click(function(){
emailvar = $(".emfield").val();
name1var = $(".nam1field").val();
name2var = $(".nam2field").val();
alert(emailvar);
$.cookie("sec8email", emailvar);
$.cookie("sec8name1", name1var);
$.cookie("sec8name2", name2var);
});
var emvar = $.cookie("sec8email");
var name1 = $.cookie("sec8name1");
var name2 = $.cookie("sec8name2");
}(window, jQuery));
The function you pass into ready is actually executed before the DOM is ready since you call it. This should call it when the DOM is ready and still maintain what you want to do.
(function(window, $){
$(document).ready(function(){
var emailvar;
var name1var;
var name2var;
$(".sbmtfrm").click(function(){
emailvar = $(".emfield").val();
name1var = $(".nam1field").val();
name2var = $(".nam2field").val();
alert(emailvar);
$.cookie("sec8email", emailvar);
$.cookie("sec8name1", name1var);
$.cookie("sec8name2", name2var);
});
var emvar = $.cookie("sec8email");
var name1 = $.cookie("sec8name1");
var name2 = $.cookie("sec8name2");
});
}(window, jQuery));
function(window,jQuery){...}(window,jQuery) will execute the function and return undefined, so you would be doing $document.ready(undefined)

How to get label's id?

This is index.html
<html>
<head>
<script language="javascript" type="text/javascript" src="add.js"></script>
<script language="javascript" type="text/javascript" src="get.js"></script>
</head>
<body>
<div id="list">
<form id="programs" name="programs">
</form>
<input type="button" value="add" onClick="add();" />
<input type="button" value="delete" onClick="get();" />
</div>
</body>
</html>
This is add.js
var program_number = 0;
function add()
{
var program_name = "program_sample";
var formID = document.getElementById("programs");
var labelTag = document.createElement("label");
var inputTag = document.createElement("input");
var txtNode = document.createTextNode("program " + program_number);
var brTag = document.createElement("br");
// set input attribute
inputTag.setAttribute("type", "checkbox");
inputTag.setAttribute("name", program_name);
inputTag.setAttribute("value", "program" + program_number);
// set label attribute
labelTag.setAttribute("id", "program_label" + program_number);
labelTag.appendChild(inputTag);
labelTag.appendChild(txtNode);
labelTag.appendChild(brTag);
formID.appendChild(labelTag);
program_number++;
}
This is get.js
function get()
{
var programs = document.programs;
for(var i = 0; i < programs.length; i++)
console.log(programs[i].id);
}
Hello, I want to get the label's id dynamically. add.js code makes it. (below)
<label id="program_label0>
<input type="checkbox" name="program_sample" value="program0" />
program 0<\br>
</label>
If those run normally, the result can be "program_label1", "program_label2", "program_label3" ...
but the result of get.js is just a blank. What should I do to get label's id ..?
or Where my code is wrong ..?
Inside your 'get.js' you could try either
var programs = document.getElementById("programs");
or
var programs = document.forms["programs"];
or
var programs = document.forms[0];
The last one will work only if the form you are referring to is only presented first inside DOM tree.
I see a few problems:
Inputs in the beginning html are outside the form...(Please refer to w3schools form basics)
Instead of inputTag.setAttribute("type", "checkbox");, you should use inputTage.type = "checkbox";
There is no such thing as documents.programs. To access your programs DOM element, please do as in your add.js and document.getElementById("programs");
You do not seem clear on how basics work. - var formID = document.getElementById("programs"); will not return a formID... will return a DOM element. Please read more basic tutorials. Start at - w3schools
First: Why are you using setAttribute over setting the properties?
Second:
var programs = document.getElementById("programs");
More than likely you mean to access window.programs in your code, which only works had that element been in the document when you loaded the page.
When you create an element and add it to the DOM, it does not update the global object (here called window), with that new property name.
You should access form element with `document.programs.elements[i]. So you have missed "elements" which is collection of form elements.

Inserting object properties into text fields based on drop down menu selection

I have recently started using javascript and perhaps got a little in over my head. I'm trying to create a tool for one of my other hobbies that creates coordinates for fences from x1,y1 to x2,y2.
The part that I am getting hung up on right now is part of the UI. I want the user to be able to select their desired fence from a dropdown menu and then for the rest of the information pertaining to the fence (name, length, width, direction, etc.) to be filled into the input fields below. From there they will be referenced in the math portion which I already have done.
I want the fence pieces to be objects because I'm going to add more eventually and perhaps allow the user to add more and I figured that was the easiest more user friendly way to go about it.
I have managed to get to the point where the options are in the dropdown menu, I can select them, and it will fill the piece name in with the value which is the name but I cannot figure out how to access the length, width, height, etc.
This is my first project outside of Code Academy and a little bit I did 10 years ago in High School. That being said, if you notice that I am doing something else stupid, feel free to point it out. The answers for other's questions here have already been a huge source of help for me as I worked on this, so thank you for that and for the future help.
<script>
//Start Variable Library
var dropMenuPieceName = 0;
var dropMenuPieceName = 0;
//End Variable Library
// Start Function Library
var fencePieceDropDown = function(dropDownMenuID) {
var dropMenu = document.getElementById(dropDownMenuID);
for(var i = 0; i < fenceArray.length; i++) {
var dropMenuOption = document.createElement("option");
var dropMenuPieceName = fenceArray[i].name;
var dropMenuPieceName = fenceArray[i].length;
dropMenuOption.innerHTML = fenceArray[i].model;
dropMenuOption.value = fenceArray[i].name;
var dropMenuIndex = 1;
dropMenu.add(dropMenuOption,dropMenuIndex);
};
};
//End Function Library
// Start Fence Object Library
function Fence(name,model,length,width,direction,x_offSet,y_offSet,z_offSet,r_offSet) {
this.name = name;
this.model = model;
this.length = length;
this.width = width;
this.direction = direction;
this.x_offSet = x_offSet;
this.y_offSet = y_offSet;
this.z_offSet = z_offSet;
this.r_offSet = r_offSet;
};
var fenceArray = new Array();
var plot_ohrada = new Fence
("plot_ohrada","plot_ohrada",3,0.1,0.02,0,0,0,0);
fenceArray[0] = plot_ohrada;
var plot_ohrada_pruchozi = new Fence
("plot_ohrada_pruchozi","plot_ohrada_pruchozi",4,0.2,0.02,0,0,0,0);
fenceArray[1] = plot_ohrada_pruchozi;
var plot_ohrada_zlomena = new Fence
("plot_ohrada_zlomena","plot_ohrada_zlomena",5,0.3,0.03,0,0,0,0);
fenceArray[2] = plot_ohrada_zlomena;
//End Fence Object Library
</script>
</head>
<body>
<form name="primPieceSection">
<div align="center">
Piece Model:
<select id="primPieceModel" >
<option value = 0>Custom Piece</option>
<select><br /><br /><br />
Piece Name: <input type="text" id="primPieceName" placeholder="Insert Template Name"><br />
Piece Length: <input type="text" id="primPieceLength" value=0><br />
Piece Width: <input type="text" id="primPieceWidth" value=0><br />
Piece Direction: <input type="text" id="primPieceDir" value=0><br />
</div>
</form>
<script>
var primPieceNameField = document.getElementById("primPieceName");
var primPieceLengthField = document.getElementById("primPieceLength");
var primPieceModelDrop = document.getElementById("primPieceModel");
primPieceModelDrop.onchange = function() {
primPieceNameField.value = this.value; ///this should return the object's name
primPieceLengthField.value = this.value; ///this should return the object's length. I just put in this.value while I was testing it.
};
fencePieceDropDown("primPieceModel");
</script>
In your case, the value of each dropdown option should be not its name, but rather the index of the corresponding fence in the fenceArray, which is i. Then, inside primPieceModelDrop.onchange, you will use fenceArray[this.value] to access the selected fence object.
So, you need to replace this line:
dropMenuOption.value = fenceArray[i].name;
with this:
dropMenuOption.value = i;
And then rewrite the onchange handler as follows:
primPieceModelDrop.onchange = function() {
primPieceNameField.value = fenceArray[this.value].name;
primPieceLengthField.value = fenceArray[this.value].length;
};
What you’re doing is perfectly reasonable for a beginner, but you should understand that it’s a somewhat simplistic, low-level approach. As you become more confident in JS, and as your project grows, you may find it easier to employ a framework such as AngularJS.

Categories