from a html form to javascript - javascript

I have a form that requires three inputs as follows:
<form>
<input name="mn"
type="number"
min="1"
value="1">
<input name="mx"
type="number"
min="2"
value="10">
<input name="step"
type="number"
min="1"
value="1">
<input onclick="myfunc()"
type="submit"
value="calculate">
</form>
all i require is to be able to access the three fields directly in javascript. I do not need to pass the information anywhere else.
Could anyone point me in the right direction? I have read examples where there has been one input, but not multiple.
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")
var mx = document.getElementsByName("mx")
var step = document.getElementsByName("step")
alert((mn + mx) / step)
}
</script>

Give your form an id like so
<form id="myForm">
The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them.
Try instead
var frm = document.forms["myForm"];
var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );
var result = ( _mn + _mx ) / _step;

I'd start with giving each input an id then i could use:
var min = document.getElementById('mn')
and so on. To access the value you simply would call
min.value
Also there is no point in removing the i from min and the a from max. That is not optimized just hard to read and understand.

Try this:
<script type="text/javascript">
function myfunc() {
var mn = document.getElementsByName("mn")[0].value;
var mx = document.getElementsByName("mx")[0].value;
var step = document.getElementsByName("step")[0].value;
var top = mn / mx;
alert(top / step);
}
</script>

if u need to access to the values of the inputs change your code to:
function myfunc() {
var mn = document.getElementsByName("mn")[0];
var mx = document.getElementsByName("mx")[0];
var step = document.getElementsByName("step")[0];
// you may need to validate your values here, like step.value != 0
alert((mn.value + mx.value) / step.value)
}

Related

How to fix "If statement" from adding variables exponentially?

I am trying to use a set of range sliders to impact each other in various ways. My If the statement is working correctly the first time I change a value, but the second time I change a value, it is adding the entire value instead of the change.
I've tried everything I know so far on how to resolve this, but breaks and continues do not seem to be fixing the problem.
<form>
<Label for="sliderBarOne">Ready</Label>
<input type="range" id="sliderBarOne" min="0" max="100" step="0.01" value="0" onchange="this.form.rangeOne.value=this.value">
<input type="number" id="rangeOne" value="0" onchange="this.form.sliderBarOne.value=this.value">
<br>
<Label for="sliderBarTwo">ACW</Label>
<input type="range" id="sliderBarTwo" min="0" max="100" step="0.01" value="0" onchange="this.form.rangeTwo.value=this.value">
<input type="number" id="rangeTwo" value="0" onchange="this.form.sliderBarTwo.value=this.value">
<br>
<Label for="sliderBarThree">Extra</Label>
<input type="range" id="sliderBarThree" min="0" max="100" step="0.01" value="0" onchange="this.form.rangeThree.value=this.value">
<input type="number" id="rangeThree" value="0" onchange="this.form.sliderBarThree.value=this.value">
<br>Sum: <span id="sum">0</span>
</form>
<script>
document.getElementById("sliderBarOne").addEventListener("change", updateReady);
document.getElementById("sliderBarTwo").addEventListener("change", updateACW);
document.getElementById("sliderBarThree").addEventListener("change", updateExtra);
document.getElementById("rangeOne").addEventListener("change", updateReady);
document.getElementById("rangeTwo").addEventListener("change", updateACW);
document.getElementById("rangeThree").addEventListener("change", updateExtra);
function updateReady() {
var readyBox = document.getElementById('sliderBarOne');
var acwBox = document.getElementById('sliderBarTwo');
var extraBox = document.getElementById('sliderBarThree');
var readyField = document.getElementById('rangeOne');
var acwField = document.getElementById('rangeTwo');
if (readyBox.value < 100 || readyField.value < 100) {
acwBox.value = 100 - parseFloat(readyBox.value);
//Set Slider Values Into Fields
readyField.value = readyBox.value;
acwField.value = acwBox.value;
extraField.value = extraBox.value;
}
updateSum();
}
function updateACW() {
var readyBox = document.getElementById('sliderBarOne');
var acwBox = document.getElementById('sliderBarTwo');
var extraBox = document.getElementById('sliderBarThree');
updateSum();
}
function updateExtra() {
var readyBox = document.getElementById('sliderBarOne');
var acwBox = document.getElementById('sliderBarTwo');
var extraBox = document.getElementById('sliderBarThree');
var readyField = document.getElementById('rangeOne');
var acwField = document.getElementById('rangeTwo');
var extraField = document.getElementById('rangeThree');
if (extraBox.value > 0 || extraField.value > 0) {
readyBox.value = parseFloat(readyBox.value) - parseFloat(extraBox.value);
acwBox.value = parseFloat(acwBox.value) + parseFloat(extraBox.value);
//Set Slider Values Into Fields
readyField.value = readyBox.value;
acwField.value = acwBox.value;
extraField.value = extraBox.value;
}
updateSum();
}
</script>
The first time I enter a value into Ready, it properly subtracts that value from 100 to provide ACW.
Then, when I put a value into Extra, it accurately subtracts that value from Ready and adds to ACW. For instance, Ready 95, ACW 5. Making Extra 1 makes Ready 94 and ACW 6. The problem is, when I change Extra to 2, it makes Ready 92 and ACW 8 instead of Ready 93 and ACW 7.
I'm not sure how to grab the change in the value on each change.
your updatesum() is not defined and your extrafield is not defined in updateready() function
Because the values are changed before. You first change them by 1, and then change them by 2. Hence, it means the extra is 3! Unless you reload the page to reinitialize the values to 95 and 6 and then apply extra 2. It will give you 93 and 7.
To solve the problem you can write an initialize function that initializes the values, and then call the function at the first line of the updateExtra function.
OmG provided the inspiration to create an initial value field. So, I adjusted the code as follows. Thanks OmG!
function updateExtra() {
var readyBox = document.getElementById('sliderBarOne');
var acwBox = document.getElementById('sliderBarTwo');
var extraBox = document.getElementById('sliderBarThree');
var readyField = document.getElementById('rangeOne');
var acwField = document.getElementById('rangeTwo');
var extraField = document.getElementById('rangeThree');
var initialReady = document.getElementById('initialReady');
var initialACW = document.getElementById('initialACW');
if (extraBox.value > 0 || extraField.value > 0) {
readyBox.value = parseFloat(initialReady.value) - parseFloat(extraBox.value);
acwBox.value = parseFloat(initialACW.value) + parseFloat(extraBox.value);
//Set Slider Values Into Fields
readyField.value = readyBox.value;
acwField.value = acwBox.value;
extraField.value = extraBox.value;
}
updateSum();
}

get the quotient of two textbox which has an onChange event

I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.
function sum(){
var ua = document.getElementById('ua').value;
var ub = document.getElementById('ub').value;
var result = parseInt(ua) + parseInt(ub);
if (!isNaN(result)) {
document.getElementById('tu').value = result;
document.getElementById('tu').dispatchEvent(new Event('change'));
}
}
function suma(){
var ua = document.getElementById('ua').value;
var ga = document.getElementById('ga').value;
var result = parseInt(ua) * parseInt(ga);
if (!isNaN(result)) {
document.getElementById('uu').value = result;
document.getElementById('uu').dispatchEvent(new Event('change'));
}
}
function sumb(){
var ub = document.getElementById('ub').value;
var gb = document.getElementById('gb').value;
var result = parseInt(ub) * parseInt(gb);
if (!isNaN(result)) {
document.getElementById('a').value = result;
document.getElementById('a').dispatchEvent(new Event('change'));
}
}
function s(){
var uu = document.getElementById('uu').value;
var a = document.getElementById('a').value;
var result = parseInt(uu) + parseInt(a);
if (!isNaN(result)) {
document.getElementById('tt').value = result;
document.getElementById('tt').dispatchEvent(new Event('change'));
}
}
function g(){
var tt = document.getElementById('tt').value;
var tu = document.getElementById('tu').value;
var result = parseFloat(tt) / parseFloat(tu);
if (!isNaN(result)) {
document.getElementById('gpa').value = result;
}
}
<input type="text" id="ua" name="ua" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="suma();">
<input type="text" id="uu" name="uu" size="7" onchange="s();"/>
<input type="text" id="ub" name="ub" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="sumb();">
<input type="text" id="a" name="a" size="7" onchange="s();"/>
<input type="text" id="tu" name="tu" onchange="g();"/>
<input type="text" id="tt" name="tt" onchange="g();"/>
<label>GPA</label>
<input type="text" id="gpa" />
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).
That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.
As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?
In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:
var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');
function updateQuotient () {
var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
if (!isNaN(result)) {
resultElement.value = result;
}
}
dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);
<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">

how to pass calculated values using javascript

the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please
you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....
Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);
set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).
//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Passing JQuery value to html and then tally the totals with onclick

I am trying to pass on JQuery values to hidden textboxes (to send as a form later) as well as divs t
hat displays on the front end. I also want to tally these items as the value is passed to them. I have Frankensteined this bit of code which passes on the value to the the input boxes and the divs and it also tallies them onclick. I am just struggling to get the sum to display in #total_div. Can anyone point me in the right direction please?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#my_div').click(function() {
$('#my_value_1').val("100");
$('#my_value_1_div').html( "100" );
$('#my_div').click(addNumbers('total'));
});
});
$(document).ready(function(){
$('#my_div_2').click(function() {
$('#my_value_2').val("200");
$('#my_value_2_div').html( "200" );
$('#my_div_2').click(addNumbers('total'));
});
});
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
</script>
<h2>My pretty front end</h2>
<div id="my_div">ADD THIS VALUE 1</div>
<div id="my_div_2">ADD THIS VALUE 2</div>
VALUE 1: <div id="my_value_1_div">VALUE 1 GOES HERE</div>
VALUE 2: <div id="my_value_2_div">VALUE 2 GOES HERE</div>
TOTAL: <div id="total_div">SUM MUST GO HERE</div>
<h2>My hidden Form</h2>
Value 1: <input type="text" id="my_value_1" name="my_value_1" value="0"/>
Value 2: <input type="text" id="my_value_2" name="my_value_2" value="0"/>
<input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
Total: <input type="text" id="total" name="total" value=""/>
EDIT
Ok so thanks to the advice I got the above working but now I need to clear the amounts. This is what I have done, it is almost there I think but I'm getting the incorrect sum.
$('#clear').click(function() {
$('#my_value_1').val('0');
$('#my_value_1_div').html( "0" );
$('#clear').click(minusNumbers('total'));
});
function minusNumbers()
{
var minval1 = parseInt(document.getElementById("my_value_1").value);
var minval2 = parseInt(document.getElementById("total").value);
var minansD = document.getElementById("total");
minansD.value = minval2 - minval1;
$('#total_div').text(minansD.value);
}
Update #total_div text in addNumber function as,
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
$('#total_div').text(ansD.value);
}
Demo
replace:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD.value = val1 + val2;
}
with:
function addNumbers()
{
var val1 = parseInt(document.getElementById("my_value_1").value);
var val2 = parseInt(document.getElementById("my_value_2").value);
var ansD = document.getElementById("total");
ansD = val1 + val2;
$('#total').val(ansD);
}
click(addNumbers('total')); first calls addNumbers with an unused parameter 'total' then gets the return value of addNumbers (null or undefined) and sets that as the click() handler for the next click.
I think you probably meant
$('#my_div').click(addNumbers);
that means, "run the addNumbers function, defined below, next time I click my_div".
or just
addNumbers();
that means, "run the addNumbers function now" (at the first click)
Note though that when you click and call addNumbers, one of the numbers may not yet be copied, so you would be adding 100+"" or ""+200 so you really have to think about what you want to do.

Categories

Resources