Please can you help me with my IF statements? - javascript

Whats wrong with the following code (I think its something to do with the if statements), i've tried looking it up online, but to no success?
<form action="#" method="post" name="formSeven">
<p><input type="text" name="z11" value="" size="4" /> <span> Adjusted BMI </span></p>
<p><input type="text" name="z12" value="" size="4" /> <span> Age in years </span></p>
<p><input type="text" name="z13" value="" size="4" /> <span> Male or Female </span></p>
<p><input type="text" name="result7" value="" size="4" /> <span> BF% </span></p>
<p><input onclick="calculate7()" type="BUTTON" value="Calculate" /></p>
</form>
<script type="text/javascript">//
function calculate7() {
var x = document.formSeven.z11.value;
var y = document.formSeven.z12.value;
var z = document.formSeven.z13.value;
if (z == "Female"){
document.formSeven.result7.value = x+y-5.4;
}
else if (z == "Male") {
document.formSeven.result7.value = x+y-16.2;
}
}
// ]]></script>

the best to input gender is to make a select, because you won't have to worry about mistake from user :
<select id="gender" >
<option value="0" selected="selected">Female</option>
<option value="1">Male</option>
</select>
then in your javascript
(parseInt(document.getElementById('gender').value) === 0) ? document.formSeven.result7.value = x+y-5.4:document.formSeven.result7.value = x+y-16.2;

Use
if (z === "Female"){
document.formSeven.result7.value = x+y-5.4;
}

if (z == "Female")
document.formSeven.result7.value = x+y-5.4;
else if (z == "Male")
document.formSeven.result7.value = x+y-16.2;

The values are strings, so instead of adding the numbers, you will be concatenating the strings.
Parse the strings into numbers:
var x = parseInt(document.formSeven.z11.value, 10);
var y = parseInt(document.formSeven.z12.value, 10);

That's the shortest way to do what you want.
It also gives you some error margin as it is case insensitive.
document.formSeven.result7.value=(z.toLowerCase()=='female'?(x+y-5.4):(x+y-16.2));
here
document.formSeven.result7.value=(z.toLowerCase()=='female'?(x+y-5.4):(z.toLowerCase()=='male'?(x+y-16.2):''));
replace the latest z with whatever value you want.
Here is your full code:
<form action="#" method="post" name="formSeven">
<p><input type="text" name="z11" value="" size="4" /> <span> Adjusted BMI </span></p>
<p><input type="text" name="z12" value="" size="4" /> <span> Age in years </span></p>
<p><input type="text" name="z13" value="" size="4" /> <span> Male or Female </span></p>
<p><input type="text" name="result7" value="" size="4" /> <span> BF% </span></p>
<p><input onclick="calculate7()" type="BUTTON" value="Calculate" /></p>
</form>
<script type="text/javascript">//
function calculate7() {
var x = document.formSeven.z11.value;
var y = document.formSeven.z12.value;
var z = document.formSeven.z13.value.toLowerCase();
var r = document.formSeven.result7;
r.value=(z=='female'?(x+y-5.4):(z=='male'?(x+y-16.2):r.value));
}
// ]]></script>
You can also clean up the code a little more
<form action="#" method="post" name="formSeven">
<p><input type="text" name="z11" size="4" /> <span> Adjusted BMI </span></p>
<p><input type="text" name="z12" size="4" /> <span> Age in years </span></p>
<p><input type="text" name="z13" size="4" /> <span> Male or Female </span></p>
<p><input type="text" name="result7" size="4" /> <span> BF% </span></p>
<p><input onclick="calculate7()" type="button" value="Calculate" /></p>
</form>
<script type="text/javascript">
function calculate7() {
var f=document.formSeven,
x=f.z11.value,
y=f.z12.value,
z=f.z13.value.toLowerCase(),
r=f.result7;
r.value=(z=='female'?(x+y-5.4):(z=='male'?(x+y-16.2):r.value));
}
</script>

Related

Button to update the text in a search field but entering several values in sequence?

With this code we can send a single value to the search field. Now, taking into account this example, how do we insert more values in sequence with the same button, for example: value 1, value 2, value 3 ...?
http://jsfiddle.net/g506bxL4/1/
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
function setValue() {
document.getElementById('bbb').value = "valor 1";
}
</script>
You simply make a counter:
var valor = 0;
function setValue() {
valor++;
document.getElementById('bbb').value = "valor " + valor;
}
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
These are the two solutions, one inserts the values ​​randomly and the other inserts in order. They are both working perfectly.
http://jsfiddle.net/62wLqz37/1/
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
const myValues = ['Decoration', 'Health', 'Fun', 'Yesterday 4'];
function setValue() {
const randomNum = Math.floor(Math.random() * myValues.length); ;
document.getElementById('bbb').value = myValues[randomNum];
}
</script
http://jsfiddle.net/7bpaL5hy/
<form id="form1" name="form1" method="post">
<p>
<input type="button" name="set_Value" id="set_Value" value="submit" onclick="setValue()" />
</p>
<p>
<label>
<input type="text" name="bbb" id="bbb" />
</label>
</p>
</form>
<script type="text/javascript">
const myValues = ['Decoration', 'Health', 'Fun', 'Yesterday 4'];
let myInd = 0;
function setValue() {
document.getElementById('bbb').value = myValues[myInd];
myInd = myInd >= (myValues.length - 1) ? 0 : myInd+1;
}
</script>

How can I set the value in a textbox on form load?

This is what I tried for setting the textbox values but it doesn't seem to be working. I want the textboxes to have the values in them when the page loads. the function is within the script tag.
function setMSRP()
{
var MSRP = "$29,120.00";
var destinationCharge = "$875.00";
var rebate = "-$10,000.00";
var taxes = "6%"
var titlesAndFees = "$209.00";
document.getElementById("txtMSRP").value = MSRP;
document.getElementById("txtDestinationCharge").value = destinationCharge;
document.getElementById("txtRebates").value = rebate;
document.getElementById("txtTaxes").value = taxes;
document.getElementById("txtElectricTitleAndFees").value = titlesAndFees;
}
</script>
</head>
<body onload="setMSRP()">
<form>
<h1>Calculate Focus Price</h1>
<hr/>
<label for="txtMSRP">MSRP:</label>
<input autofocus id="txtMSRP" type="text" readonly="readonly"/>
<br/>
<label for="txtDestinationCharge">Destination Charge:</label>
<input type="text" id="txtDestinationCharge" readonly="readonly"/>
<br/>
<label for="txtRebates">Rebates:</label>
<input type="text" id="txtRebates" readonly="readonly"/>
<br/>
<label for="txtTaxes">Taxes:</label>
<input type="text" id="txtTaxes" readonly="readonly"/>
<br/>
<label for="txtElectricTitleAndFees">Electric Title and Fees:</label>
<input type="text" id="txtElectricTitleAndFees" readonly="readonly"/>
<br/>
<input type="button" id="btnCalculateTotal" onclick="calcTotal()"
</form>
</body>
You have some syntax errors in code. Look at the modified example below:
<html>
<head>
<script>
function setMSRP() {
var MSRP = "$29,120.00";
var destinationCharge = "$875.00";
var rebate = "-$10,000.00";
var taxes = "6%"
var titlesAndFees = "$209.00";
document.getElementById("txtMSRP").value = MSRP;
document.getElementById("txtDestinationCharge").value = destinationCharge;
document.getElementById("txtRebates").value = rebate;
document.getElementById("txtTaxes").value = taxes;
document.getElementById("txtElectricTitleAndFees").value = titlesAndFees;
}
</script>
</head>
<body onload="setMSRP()">
<form>
<h1>Calculate Focus Price</h1>
<hr/>
<label for="txtMSRP">MSRP:</label>
<input autofocus id="txtMSRP" type="text" readonly="readonly" />
<br/>
<label for="txtDestinationCharge">Destination Charge:</label>
<input type="text" id="txtDestinationCharge" readonly="readonly" />
<br/>
<label for="txtRebates">Rebates:</label>
<input type="text" id="txtRebates" readonly="readonly" />
<br/>
<label for="txtTaxes">Taxes:</label>
<input type="text" id="txtTaxes" readonly="readonly" />
<br/>
<label for="txtElectricTitleAndFees">Electric Title and Fees:</label>
<input type="text" id="txtElectricTitleAndFees" readonly="readonly" />
<br/>
<input type="button" id="btnCalculateTotal" onclick="calcTotal()">
</form>
</body>
</html>
I want the textboxes to have the values in them when the page loads.
You don't need JS for this:
<input id="txtMSRP" type="text" value="<your_value>" />
If you wanted placeholders inside the input[type=text], simply use
var textbox = document.querySelector("#textbox");
textbox.setAttribute("placeholder", "This is the Placeholder");
Or use the HTML Attribute to set the value/placeholder:
<input type="text" id="textbox" value="Hello" placeholder="Introductory Statement" />

Passing variable from script to HTML

I'm sure I must be missing something really silly here, but I can't seem to pass a value from my javascript function to my html form.
I have the following code:
<form class="form">
<p>Potencia a Instalar (Watts)
<br />
<span class="form"><input type="text" name="watts_to_install" value="" size="40" id="watts_to_install" required />
</span>
</p>
<p>Panel a ser utilizado<br />
<span class="form">
<select name="panel" class="form" id="panel">
<option id="Hanwha">Hanwha 250W</option>
<option id="Sharp">Sharp 250W</option>
</select>
</span>
</p>
<button onclick="Process1()">Nivel 1</button>
<span class="form">
<p>Potencia Maxima de Panel</p>
<input type="text" id="max_power" value="">
<br />
<p>Cantidad a Instalar</p>
<input type="text" id="quantity" value="">
</span>
</form>
<script type="text/javascript">
function Process1()
{
var power = document.getElementById('watts_to_install').value;
var panel = document.getElementById('panel').value;
switch(panel)
{
case 'Hanwha':
var power_panel = 250;
var panel_quantity = power/power_panel;
document.getElementById('max_power').value = power_panel;
document.getElementById('quantity').value= panel_quantity;
break;
case 'Sharp':
break;
}
}
</script>
The problem is that the page loads and...nothing happends. I see the information in my URL but nothing else. I tried passing it using .innerHTML instead of .value but it was to no avail. I know I must be missing something really easy but I just can't seem to find it.
You need to replace id with value on your option tags:
function Process1() {
var power = document.getElementById('watts_to_install').value;
var panel = document.getElementById('panel').value;
switch (panel) {
case 'Hanwha':
var power_panel = 250;
var panel_quantity = power / power_panel;
document.getElementById('max_power').value = power_panel;
document.getElementById('quantity').value = panel_quantity;
break;
case 'Sharp':
break;
}
}
<form class="form">
<p>Potencia a Instalar (Watts)
<br />
<span class="form"><input type="text" name="watts_to_install" value="" size="40" id="watts_to_install" required /></span>
</p>
<p>Panel a ser utilizado
<br />
<span class="form"><select name="panel" class="form" id="panel">
<option value="Hanwha">Hanwha 250W</option>
<option value="Sharp">Sharp 250W</option>
</select></span>
</p>
<button onclick="Process1()">Nivel 1</button>
<span class="form">
<p>Potencia Maxima de Panel</p>
<input type="text" id="max_power" value="">
<br />
<p>Cantidad a Instalar</p>
<input type="text" id="quantity" value="">
</span>
</form>

Copy text from text fields to textarea + labels

[SOLVED] I have a script that copies text from text fields to text area. My question is how can I upgrade this script so it would copy labels to? Or if I could somehow add extra text before field value?
This is my HTML:
<label>Input1: </label> <input type="text" name="i1" class="entry" id="field_1" value="" /> <br />
<label>Input2: </label> <input type="text" name="i2" class="entry" id="field_2" value="" /><br />
<label>Input3: </label> <input type="text" name="i3" class="entry" id="field_3" value="" /><br />
<label>Input4: </label> <input type="text" name="i4" class="entry" id="field_4" value="" /><br />
<label>Input5: </label> <input type="text" name="i5" class="entry" id="field_5" value="" /><br /><br />
<input type="button" name="b" value="copy" /><br /><br />
<textarea class="box" name="t" rows="5"> </textarea>
And this:
<script type="text/javascript">
$( document ).ready(function() {
$("input:button").click(function() {
var values = "";
$("input:text").each(function(i) {
values += (i > 0 ? "\n" : "") + this.value;
});
$("textarea").val(values);
});
});
</script>
EDIT: Is there any way of not showing text if some of the text fields are empty?
I added if(this.value.length > 1) and when copy is pressed it shows "undefined".
try
$( document ).ready(function() {
$("input:button").click(function() {
var values = "";
$("input:text").each(function(i) {
var text=$(this).prev("label").text();
values+=text+" " ;
values += (i > 0 ? "\n" : "") + this.value;
});
$("textarea").val(values);
});
});
DEMO

Real time updating of Javascript Calculator answer

Is there a way to get a javascript calculator to calculate an answer as a user types instead of having to press a "calculate" button like in this example?
<form name="form" id="form">
<input type="Text" name="weight" size="4"> Weight (in Kilos)
<input type="Text" name="height" size="4"> Height (in Centimeters)<br>
<input type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
</form>
Using onblur is an improvement but you still have to click out of the text box to blur the input to get the answer. Like I say, I'd prefer the answer to update in real time. Any suggestions? Thanks!
If the user is typing, you can use the keyup event. So basically, everytime the user types a key, your event handler fires and can update the view/display.
Use onkeyup.
e.g.
<form name="form" id="form">
<input type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
</form>
jsFiddle example.
EDIT: Changed to onkeyup after finding onkeypress didn't work for me in Chrome.
HTML
<form name="form" id="form">
<input class="bmi_input" type="Text" name="weight" size="4"/> Weight (in Kilos)
<input class="bmi_input" type="Text" name="height" size="4"/> Height (in Centimeters)
<input class="bmi_input" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"/> BMI
</form>
Javascript
function calculateBMI() {
console.log("I'm here");
}
var els = document.getElementsByClassName("bmi_input");
var sz = els.length;
for(var n = 0; n < sz; ++n) {
els[n].onkeyup = calculateBMI;
}
http://jsfiddle.net/dbrecht/94hxS/
You could handle the onChange event in each of the input text boxes, calling your calculate function:
<form name="form" id="form">
<input type="Text" name="weight" size="4" onChange="calculateBMI()"> Weight (in Kilos)
<input type="Text" name="height" size="4" onChange="calculateBMI()"> Height (in Centimeters)<br>
<input type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
</form>
Here is a simple example of two user text inputs, which "instantly" calculate the answer based on the called JavaScript function (The functions are also included). In addition, this code provides the option to also use a button (it is currently commented out). Hope this helps!
HTML:
<body>
<div id="form-main">
<div id="form-div">
<form class="form" id="form1" method="post">
<p class="celcius"><h2 style="color:#FFF">Input:</h2>
<input name="celsius" type="text" class="feedback-input" placeholder="Temperature (Celsius)" onkeyup="Conversion()" id="celsius" />
</p>
<hr>
<h2 style="color:#FFF">Result:</h2>
<p class="fahrenheit">
<input name="fahrenheit" type="text" class="feedback-input" id="fahrenheit" onkeyup="Conversion2()" placeholder="Temperature (Fahrenheit)" />
</p>
<!--
<div class="submit">
<input type="button" value="CONVERT" id="button-blue" onClick="Conversion()"/>
<div class="ease"></div>
</div>
-->
</form>
</div>
</body>
JavaScript:
function Conversion() {
var tempCels = parseFloat(document.getElementById('celsius').value);
tempFarh =(tempCels)*(1.8)+(32);
document.getElementById('fahrenheit').value= tempFarh;
}
function Conversion2() {
var tempFarh = parseFloat(document.getElementById('fahrenheit').value);
tempCels =(tempFarh - 32)/(1.8);
document.getElementById('celsius').value= tempCels;
}

Categories