Passing variable from script to HTML - javascript

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>

Related

Disable form button and field with Javascript

I need to disable some filed and button in a form. The form shows user data and the button "Modifica" allow the user to modify field (username, mail, password). If user is worker can modify also exp and photo field. If user is manager this field are hidden.
I wrote some javascript in order to hide and disable fields but the button "modifica" seems to be blocked and I don't know why.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="all" href="../CSS/style.css" th:href="#{.../CSS/style.css}"/>
<script type="text/javascript" src="../js/updateProfile.js" th:src="#{/js/updateProfile.js}" defer> </script>
<script type="text/javascript" th:src="#{/js/loadimage.js}" defer ></script> <!--defer fa eseguire js dopo il parsing di html-->
</head>
<body>
<div class="container">
<div th:replace="header :: header"></div>
<h1>Profilo Utente</h1>
<div class="form">
<form action="updateprofile" method="post" enctype="multipart/form-data">
<p>
<label for="username">Username: </label><br>
<input type="text" id="username" name="username" th:attr="value=${session.user.username}" required/><br>
</p>
<p>
<label for="email">Mail: </label><br>
<input type="email" id="email" name="email" th:attr="value=${session.user.email}" required/><br>
</p>
<p>
<label for="password">Password: </label><br>
<input type="password" id="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Deve contenere almeno 8 caratteri di cui un numero, una lettera maiuscola e una lettera minuscola." /><br>
</p>
<div id="password-confirm-block">
<p>
<label id="text-password-confirm" for="password-confirm">Reinserisci password: </label><br>
<input type="password" id="password-confirm" />
</p>
<p id="password-message" class="error-message"></p>
</div>
<p>
Tipo di utente:<br>
<input type="radio" name="usertype" id="manager" value="manager" th:checked="${session.user.isManager!=null && session.user.isManager}" required/>
<label for="manager">Manager</label><br>
<input type="radio" name="usertype" id="worker" value="worker" th:checked="${session.user.isManager!= null && !session.user.isManager}" checked required/>
<label for="worker">Worker</label><br>
</p>
<div id="worker-data">
<p>
<label for="exp">Exp level:</label><br>
<select name="exp" id="exp">
<option value="" disabled selected>Exp level</option>
<option value="LOW" th:selected="${session.user.exp == 'LOW'}">LOW</option>
<option value="MEDIUM" th:selected="${session.user.exp == 'MEDIUM'}">MEDIUM</option>
<option value="HIGH" th:selected="${session.user.exp == 'HIGH'}">HIGH</option>
</select><br>
</p>
<p>
<label for="photo">Profile photo</label><br>
<div id="container"style="position: relative; width:300px;">
<canvas id="canvas_background" width="300px" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
<input type="file" name="photo" id="photo" accept="image/*"/><br>
</div>
<!-- TODO: Rivedere i messaggi di errore inseriti -->
<span class="error-message" th:if="${session.signupfailed}">Salvataggio non riuscito</span>
<p>
<input id="buttonModifica" type="button" value="Modifica" />
<input id="buttonAnnulla" type="reset" value="Annulla" />
<input id="buttonAggiorna" type="submit" value="Aggiorna" />
</p>
</form>
</div>
</div>
</body>
</html>
Javascript:
var username = document.getElementById("username");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordConfirmBlock = document.getElementById("password-confirm-block");
var radioWorker = document.getElementById("worker");
var radioManager = document.getElementById("manager");
var exp = document.getElementById("exp");
var photo = document.getElementById("photo");
var buttonModifica = document.getElementById("buttonModifica");
var buttonAnnulla = document.getElementById("buttonAnnulla");
var buttonAggiorna = document.getElementById("buttonAggiorna");
function init() {
view();
buttonModifica.addEventListener("click", modify, true);
buttonAnnulla.addEventListener("click", view, true);
}
init();
function modify() {
unlockImputs();
buttonAnnulla.hidden=false;
buttonAggiorna.hidden=false;
buttonModifica.hidden=true;
}
function view() {
lockImputs();
buttonAnnulla.hidden=true;
buttonAggiorna.hidden=true;
buttonModifica.hidden=false;
}
function lockImputs (){
username.readOnly=true;
email.readOnly=true;
password.readOnly=true;
passwordConfirmBlock.hidden=true;
radioManager.disabled=true;
radioWorker.disabled=true;
exp.disabled=true;
photo.disabled=true;
}
function unlockImputs (){
username.readOnly=false;
email.readOnly=false;
password.readOnly=false;
radioManager.disabled=false;
radioWorker.disabled=false;
exp.disabled=false;
photo.disabled=false;
}
If you need to disable the button "Modifica", You can just set "disabled" to true for this button's id:
document.getElementById("buttonModifica").disabled = true;
You can get that HTML_DOM with document object then you can apply event listener on it.
Then get another id to which you want to disable and apply disable property into it
For reference :
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/disabled

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" />

Html javascript Submit different form same data type, 2 buttons

Ok, so this is a bit confusing to explain but basically, I am creating a checkout page which users can either choose "delivery" or "Pickup", once chosen it 'unhides' the corresponding form which once filled out will send data to the next page. The problem is that I want to use the same id's for both forms but just add an address to the delivery one but it seems like it will only take data from the first/top form which is the takeaway-
function Delivery1() {
var x = document.getElementById("Pickup");
var y = document.getElementById("Delivery");
var w = document.getElementById("btn1");
var z = document.getElementById("btn2");
if (y.style.display === "none") {
x.style.display = "none";
y.style.display = "block";
w.style.backgroundColor = "#b20c0c";
z.style.backgroundColor = "#cc1400";
} else {
y.style.display = "none";
}
}
function Pickup1() {
var y = document.getElementById("Delivery");
var x = document.getElementById("Pickup");
var w = document.getElementById("btn1");
var z = document.getElementById("btn2");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
z.style.backgroundColor = "#b20c0c";
w.style.backgroundColor = "#cc1400";
} else {
z.style.backgroundColor = "#cc1400";
x.style.display = "none";
}
}
<center>
<button id="btn1" onclick="Delivery1()" class="btn" style="height:90px; width: 180px">Delivery</button>
<button id="btn2" onclick="Pickup1()" class="btn" style="height:90px; width: 180px">Pickup</button>
</center>
<div id="Pickup" style="display: none;">
<form action="order.html" method="post" id="checkout-order-form">
<fieldset id="fieldset-billing">
<legend>Pickup</legend>
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" data-type="string" data-message="This field cannot be empty" />
</div>
<div>
<label for="email">Phone Number</label>
<input type="text" name="email" id="email" data-type="expression" data-message="Not a valid phone address" />
</div>
<div>
<label for="country">Select Store</label>
<select name="country" id="country" data-type="string" data-message="This field cannot be empty">
<option value="">None</option>
<option value="Leopold">Leopold</option>
</select>
</fieldset>
<p><input type="submit" id="submit-order" value="Submit" class="btn" /></p>
</div>
</form>
<div id="Delivery" style="display: none;">
<form action="order.html" method="post" id="checkout-order-form">
<fieldset id="fieldset-shipping">
<legend>Delivery</legend>
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" data-type="string" data-message="This field cannot be empty" />
</div>
<div>
<label for="email">Phone Number</label>
<input type="text" name="email" id="email" data-type="expression" data-message="Not a valid phone number" />
</div>
<div>
<label for="address">Address</label>
<h3>(Must be in or in neighbouring suburbs of leopold no more than 10km)</h3>
<input type="text" name="address" id="address" data-type="string" data-message="This field cannot be empty" />
</div>
</fieldset>
<p><input type="submit" id="submit-order" value="Submit" class="btn" /></p>
</div>
</form>
</div>
</div>
<footer id="site-info">
Copyright © Fu Chinese
</footer>
If its needed i can post the javascript form but its quite long. If anyone can help me with a solution or easier way to do this that would be great. Thanks :)
You cannot have more than one element with the same Id.
The purpose of the ID is to identify elements on page, therefore, you can have only one element per ID.
You can have multiple elements with the same "name" but not with the same ID.
To solve your problem, do the following:
Put a different ID for each form.
Put the attribute form in the input tag in your form.
Form 1:
<form action="order.html" method="post" id="checkout-order-form-billing">
<input type="submit" id="submit-order" value="Submit" class="btn" form="checkout-order-form-billing" />
Form 2:
<form action="order.html" method="post" id="checkout-order-form-shipping">
<input type="submit" id="submit-order" value="Submit" class="btn" form="checkout-order-form-shipping" />
This way, the input tag knows which form to submit.
Hope it helps.

Please can you help me with my IF statements?

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>

Combo box for all control

I created a filterable drop Down List using JavaScript. This is the List Box Coding.
<select name="d1" class="leftselect" id="d1" size="5" ondblclick="DropDownTextToBox('d1','t1');" style="display:none;" >
<option>axcsus-COMMON STOCK</option>
<option>aces</option>
<option>bdfs</option>
<option>befs</option>
<option>behs</option>
<option>dfgh</option>
<option>dhes</option>
<option>dwww</option>
<option>pass</option>
<option>pass</option>
</select>
I created 4 Text Field and a arrow character. If i click the arrow character , I'll show the list at the bottom of the control.
<div id="div_name" style="float:left;z-index: 20;">
<input name="t1" type="text" id="t1" onkeyup="value_filtering('d1','t1');" onkeypress="onEnter(event,'d1','t1')" />
<input type="button" class="rightselect" onclick="displayList('d1','t1');" value="▼" />
</div>
<div class="inputbox">
<input name="t2" class="inputbox" type="text" id="t2" onkeyup="value_filtering('d2','t2');" onkeypress="onEnter(event,'d2','t2')" />
<input type="button" class="leftselect" onclick="displayList('d1','t2');" value="▼" />
</div>
<div style="float:left;text-align:center;" >
<input name="t3" type="text" id="t3" onkeyup="value_filtering('d3','t3');" onkeypress="onEnter(event,'d3','t3')" />
<input type="button" class="rightselect" onclick="displayList('d1','t3');" value="▼" />
</div>
<div class="inputbox">
<input name="t4" class="inputbox" type="text" id="t4" onkeyup="value_filtering('d4','t4');" onkeypress="onEnter(event,'d4','t4')" />
<input type="button" class="leftselect" onclick="displayList('d1','t4');" value="▼" />
</div>
In the display List function I'm getting the corresponded textbox position and displayed the List Control under the Text Box. Okie. Now my problem is If i select any option in the text box, I need to display the selected value to the textbox which the listbox shown under. After selecting the value from the list box, How i find in which text box showing the List ? Dynamically how can i find the text box id ?
This is my JS code for displaying the Listbox to the corresponding TextBox.
function displayList(ele,txt)
{
vis=document.getElementById(ele);
obj=document.getElementById(txt);
if (vis.style.display==="none")
vis.style.display="block";
else
vis.style.display="none";
vis.style.position = "absolute";
//alert(getElementPosition(txt).top + ' ' + getElementPosition(txt).left);
vis.style.top = getElementPosition(txt).top+obj.offsetHeight;
vis.style.left = getElementPosition(txt).left;
}
Note : I can call this function at the click event of arrow button. I can easily pass the text Field Id. But in the case ListBox action i can't send the particular ID of the Text Field.
If you have no opposition to using jquery you can using the jquery UI built-in autocomplete which will do pretty much what you're looking for. For more advanced and nicer plugins you can try chosen
Try this.
<script>
var targetInput=null;
function displayList(ele,txt) {
vis=document.getElementById(ele);
obj=document.getElementById(txt);
targetInput = obj;
if (vis.style.display==="none") {
vis.style.display = "block";
} else {
vis.style.display = "none";
vis.style.position = "absolute";
//alert(getElementPosition(txt).top + ' ' + getElementPosition(txt).left);
vis.style.top = getElementPosition(txt).top+obj.offsetHeight;
vis.style.left = getElementPosition(txt).left;
}
}
function selectList(txt) {
if (!targetInput) return;
targetInput.value = txt.value;
txt.style.display = 'none';
}
</script>
<div id="div_name" style="float:left;z-index: 20;">
<input name="t1" type="text" id="t1" onkeyup="value_filtering('d1','t1');" onkeypress="onEnter(event,'d1','t1')" />
<input type="button" class="rightselect" onclick="displayList('d1','t1');" value="▼" />
</div>
<div class="inputbox">
<input name="t2" class="inputbox" type="text" id="t2" onkeyup="value_filtering('d2','t2');" onkeypress="onEnter(event,'d2','t2')" />
<input type="button" class="leftselect" onclick="displayList('d1','t2');" value="▼" />
</div>
<div style="float:left;text-align:center;" >
<input name="t3" type="text" id="t3" onkeyup="value_filtering('d3','t3');" onkeypress="onEnter(event,'d3','t3')" />
<input type="button" class="rightselect" onclick="displayList('d1','t3');" value="▼" />
</div>
<div class="inputbox">
<input name="t4" class="inputbox" type="text" id="t4" onkeyup="value_filtering('d4','t4');" onkeypress="onEnter(event,'d4','t4')" />
<input type="button" class="leftselect" onclick="displayList('d1','t4');" value="▼" />
</div>
<select name="d1" class="leftselect" id="d1" size="5" ondblclick="DropDownTextToBox('d1','t1');" onclick="selectList(this)" style="display:none;">
<option>axcsus-COMMON STOCK</option>
<option>aces</option>
<option>bdfs</option>
<option>befs</option>
<option>behs</option>
<option>dfgh</option>
<option>dhes</option>
<option>dwww</option>
<option>pass</option>
<option>pass</option>
</select>

Categories