Calculation between two inputs and result in another - javascript

The script below works only for the first block when you enter the quantity.
Is there any way the function performs the calculation depending on the block in which the quantity is entered.
$(document).ready(function() {
$('.somente-numero').keyup(function (e) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
var v1 = Number(document.getElementById("v1").value);
var v2 = Number(document.getElementById("v2").value);
var v7 = document.getElementById("v7").value = parseFloat(v1 * v2).toFixed(2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- bloco 1 -->
<label>preço</label> <input type="text" class="somente-numero" name="produto_solicitado[0][valor_org]" id="v1" size="10" value="100.00"/>
<label>quantidade</label> <input type="text" class="somente-numero" name="produto_solicitado[0][quantidade]" id="v2" size="10"/>
<label>total</label> <input type="text" name="produto_solicitado[0][valor_total_prod]" id="v7" size="10" readonly />
<br>
<!-- bloco 2 -->
<label>preço</label> <input type="text" class="somente-numero" name="produto_solicitado[1][valor_org]" id="x1" size="10" value="200.00"/>
<label>quantidade</label> <input type="text" class="somente-numero" name="produto_solicitado[1][quantidade]" id="x2" size="10"/>
<label>total</label> <input type="text" name="produto_solicitado[1][valor_total_prod]" id="x7" size="10" readonly />
<!-- bloco 3 -->
.................
<!-- bloco n -->

Please update your code with this script.
$(document).ready(function () {
$('.somente-numero').keyup(function (e) {
var currentVal = $(this).val();
var replaceD = currentVal.replace(/[^0-9\.]/g, '');
$(this).val(replaceD);
var v1 = Number($(this).prev().prev().val());
var v2 = Number($(this).val());
var calculatedval = parseFloat(v1 * v2).toFixed(2);
$(this).next().next().val(calculatedval);
});
});

You can keep your common block under a common class (say, .bloco). Then just find the closest .bloco and find .input1, .input2, .input3.
$(document).ready(function() {
$('.somente-numero').keyup(function (e) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
$elBloco = $(this).closest('.bloco');
var v1 = Number($elBloco.find('.input1').val());
var v2 = Number($elBloco.find('.input2').val());
var v7 = $elBloco.find('.input3').val(parseFloat(v1 * v2).toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- bloco 1 -->
<div class="bloco">
<label>preço</label> <input type="text" class="somente-numero input1" name="produto_solicitado[0][valor_org]" size="10" value="100.00"/>
<label>quantidade</label> <input type="text" class="somente-numero input2" name="produto_solicitado[0][quantidade]" size="10"/>
<label>total</label> <input type="text" class="input3" name="produto_solicitado[0][valor_total_prod]" size="10" readonly />
</div>
<br>
<!-- bloco 2 -->
<div class="bloco">
<label>preço</label> <input type="text" class="somente-numero input1" name="produto_solicitado[1][valor_org]" size="10" value="200.00"/>
<label>quantidade</label> <input type="text" class="somente-numero input2" name="produto_solicitado[1][quantidade]" size="10"/>
<label>total</label> <input type="text" class="input3" name="produto_solicitado[1][valor_total_prod]" size="10" readonly />
</div>
<!-- bloco 3 -->
.................
<!-- bloco n -->

Try this one, only javascript updated:
$(document).ready(function() {
$('.somente-numero').keyup(function (e) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
var _id = $(this).attr('id');
var result = 1.0;
$('input[id^='+_id.charAt(0)+']').each(function(i, el){
if ($(el).val().length != 0){
result *= Number($(el).val());
}
});
result = parseFloat(result).toFixed(2);
$('#'+_id.charAt(0)+'7').val(result);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- bloco 1 -->
<label>preço</label> <input type="text" class="somente-numero" name="produto_solicitado[0][valor_org]" id="v1" size="10" value="100.00"/>
<label>quantidade</label> <input type="text" class="somente-numero" name="produto_solicitado[0][quantidade]" id="v2" size="10"/>
<label>total</label> <input type="text" name="produto_solicitado[0][valor_total_prod]" id="v7" size="10" readonly />
<br>
<!-- bloco 2 -->
<label>preço</label> <input type="text" class="somente-numero" name="produto_solicitado[1][valor_org]" id="x1" size="10" value="200.00"/>
<label>quantidade</label> <input type="text" class="somente-numero" name="produto_solicitado[1][quantidade]" id="x2" size="10"/>
<label>total</label> <input type="text" name="produto_solicitado[1][valor_total_prod]" id="x7" size="10" readonly />
<!-- bloco 3 -->
.................
<!-- bloco n -->

Related

Make the first form field of a group active onfocus of div

I'm not sure if I worded the title correctly to describe my issue.
I am constructing a custom phone number 'field' within a form on my website, which is actually composed of 10 individual fields (digits), all grouped within a particular div (Id=numberContainer).
Currently, I am using some script to force the cursor to start at the first field (Id=userPhone_digit-01), no matter which field within the group the user clicks on.
The code also advances the cursor to the next 'digit' after data is entered into each field.
The code seems to work fine for all of that so far.
However, I would like to expand or modify the code, to have the cursor also start on the first field (Id=userPhone_digit-01) when the user clicks anywhere at all within the entire div (Id=numberContainer) or any elements within the div.
I have experimented with several 'tweaks', including some 'onfocus' things. But so far, I can't seem to get anything to work.
I have included a very stripped down version of the form, containing only the 'phone number' field(s).
I also left the link to the CSS in the 'head' section'.
I left out my failed attempts at tweaking the code and left in only what is currently working.
If anyone has any suggestions, it would be greatly appreciated.
Thanks, Maddison
HTML
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" href="https://www.jamiesexton.com/css/forcefield3.css">
</head>
<body>
<div class="pageContainer">
<div class="blankSpace"></div>
<div class="formContainer">
<form id="requestForm" action="/formHandler.php" method="post" enctype="multipart/form-data">
<div class="center_Wrapper">
<div class="formHeader">- THE FORM -</div>
</div>
<div class="phoneNumber_Container">
<div class="left_Wrapper">
<div class="section_Header">Phone Number</div>
<button class="phoneReset_button" title="Reset"><img src="/images/refreshbutton.png"
width="20px" height="20px"></button>
</div>
<!-- //////////////////// Start 'numberContainer' Div //////////////////// -->
<div Id="numberContainer" class="phoneField_Wrapper">
<div class="leftSpace"><img
src="https://www.jamiesexton.com/images/smallflag.jpg" width="40px"
height="24px"></div>
<p class="plusOne">+1</p>
<p class="phoneNumber_Parentheses_Left">(</p>
<input type="number" id="userPhone_digit-01" name="userPhone_digit-01" class="phoneField"
minlength="1" maxlength="1" tabindex="2" required>
<input type="number" id="userPhone_digit-02" name="userPhone_digit-02" class="phoneField"
minlength="1" maxlength="1" tabindex="3" required>
<input type="number" id="userPhone_digit-03" name="userPhone_digit-03" class="phoneField"
minlength="1" maxlength="1" tabindex="4" required>
<p class="phoneNumber_Parentheses_Right">)</p>
<input type="number" id="userPhone_digit-04" name="userPhone_digit-04" class="phoneField4"
minlength="1" maxlength="1" tabindex="5" required>
<input type="number" id="userPhone_digit-05" name="userPhone_digit-05" class="phoneField"
minlength="1" maxlength="1" tabindex="6" required>
<input type="number" id="userPhone_digit-06" name="userPhone_digit-06" class="phoneField"
minlength="1" maxlength="1" tabindex="7" required>
<p class="phoneNumber_Dash">-</p>
<input type="number" id="userPhone_digit-07" name="userPhone_digit-07" class="phoneField"
minlength="1" maxlength="1" tabindex="8" required>
<input type="number" id="userPhone_digit-08" name="userPhone_digit-08" class="phoneField"
minlength="1" maxlength="1" tabindex="9" required>
<input type="number" id="userPhone_digit-09" name="userPhone_digit-09" class="phoneField"
minlength="1" maxlength="1" tabindex="10" required>
<input type="number" id="userPhone_digit-10" name="userPhone_digit-10" class="phoneField"
minlength="1" maxlength="1" tabindex="11" required>
<div class="rightSpace"></div>
</div>
<!-- //////////////////// End 'numberContainer' Div //////////////////// -->
</div>
<!-- Start Force-Field/Next-Field Script -->
<script>
const
forceField = document.querySelector('#requestForm')
, f_nums = [...forceField.querySelectorAll('#numberContainer input')]
;
forceField.oninput = e =>
{
if ( e.target.matches('#numberContainer input[maxlength="1"]')
&& e.target.value.length===1
){
let nextOneIndx = f_nums.findIndex(el=>el===e.target) +1;
if (nextOneIndx < f_nums.length)
{
f_nums[nextOneIndx].focus();
}
else
{
let nextTab = +e.target.getAttribute('tabindex') +1;
forceField.querySelector(`[tabindex="${nextTab}"]`).focus();
}
}
}
forceField.onclick = e =>
{
if ( e.target.matches('#numberContainer input[maxlength="1"]')
&& e.target.value.length===0
){
let freeOne = f_nums.find(el=>el.value===''); // find 1st input free
if (freeOne) freeOne.focus()
}
}
</script>
<!-- End Force-Field/Next-Field Script -->
<!-- Start Clear-Number-Fields Script -->
<script>
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('.phoneField,.phoneField4');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
</script>
<!-- End Clear-Number-Fields Script -->
<div class="submitButton_Container">
<div class="center_Wrapper" ><input type="submit" class="submit__button" value="Submit"></div>
</div>
</form>
</div>
</div>
</body>
</html>
Query the numberContainer so you add an onclick event listener. Then onclick get the closest numberContainer, just in case event target is a child of the numberContainer element, we can then query the first input element using the number container element like this e.target.closest('#numberContainer').querySelector('#userPhone_digit-01')
Then any time the user clicks anywhere on the number container element, the first input will focus.
const numCont = document.getElementById('numberContainer')
numCont.onclick = e => e.target.closest('#numberContainer').querySelector('#userPhone_digit-01').focus()
const forceField = document.querySelector('#requestForm'),
f_nums = [...forceField.querySelectorAll('#numberContainer input')];
const numCont = document.getElementById('numberContainer')
numCont.onclick = e => e.target.closest('#numberContainer').querySelector('#userPhone_digit-01').focus()
forceField.oninput = e => {
if (e.target.matches('#numberContainer input[maxlength="1"]') &&
e.target.value.length === 1
) {
let nextOneIndx = f_nums.findIndex(el => el === e.target) + 1;
if (nextOneIndx < f_nums.length) {
f_nums[nextOneIndx].focus();
} else {
let nextTab = +e.target.getAttribute('tabindex') + 1;
forceField.querySelector(`[tabindex="${nextTab}"]`).focus();
}
}
}
forceField.onclick = e => {
if (e.target.matches('#numberContainer input[maxlength="1"]') &&
e.target.value.length === 0
) {
let freeOne = f_nums.find(el => el.value === ''); // find 1st input free
if (freeOne) freeOne.focus()
}
}
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('.phoneField,.phoneField4');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
<link rel="stylesheet" href="https://www.jamiesexton.com/css/forcefield3.css">
<div class="pageContainer">
<div class="blankSpace"></div>
<div class="formContainer">
<form id="requestForm" action="/formHandler.php" method="post" enctype="multipart/form-data">
<div class="center_Wrapper">
<div class="formHeader">- THE FORM -</div>
</div>
<div class="phoneNumber_Container">
<div class="left_Wrapper">
<div class="section_Header">Phone Number</div>
<button class="phoneReset_button" title="Reset"><img src="/images/refreshbutton.png"
width="20px" height="20px"></button>
</div>
<!-- //////////////////// Start 'numberContainer' Div //////////////////// -->
<div id="numberContainer" class="phoneField_Wrapper">
<div class="leftSpace"><img src="https://www.jamiesexton.com/images/smallflag.jpg" width="40px" height="24px"></div>
<p class="plusOne">+1</p>
<p class="phoneNumber_Parentheses_Left">(</p>
<input type="number" id="userPhone_digit-01" name="userPhone_digit-01" class="phoneField" minlength="1" maxlength="1" tabindex="2" required>
<input type="number" id="userPhone_digit-02" name="userPhone_digit-02" class="phoneField" minlength="1" maxlength="1" tabindex="3" required>
<input type="number" id="userPhone_digit-03" name="userPhone_digit-03" class="phoneField" minlength="1" maxlength="1" tabindex="4" required>
<p class="phoneNumber_Parentheses_Right">)</p>
<input type="number" id="userPhone_digit-04" name="userPhone_digit-04" class="phoneField4" minlength="1" maxlength="1" tabindex="5" required>
<input type="number" id="userPhone_digit-05" name="userPhone_digit-05" class="phoneField" minlength="1" maxlength="1" tabindex="6" required>
<input type="number" id="userPhone_digit-06" name="userPhone_digit-06" class="phoneField" minlength="1" maxlength="1" tabindex="7" required>
<p class="phoneNumber_Dash">-</p>
<input type="number" id="userPhone_digit-07" name="userPhone_digit-07" class="phoneField" minlength="1" maxlength="1" tabindex="8" required>
<input type="number" id="userPhone_digit-08" name="userPhone_digit-08" class="phoneField" minlength="1" maxlength="1" tabindex="9" required>
<input type="number" id="userPhone_digit-09" name="userPhone_digit-09" class="phoneField" minlength="1" maxlength="1" tabindex="10" required>
<input type="number" id="userPhone_digit-10" name="userPhone_digit-10" class="phoneField" minlength="1" maxlength="1" tabindex="11" required>
<div class="rightSpace"></div>
</div>
<!-- //////////////////// End 'numberContainer' Div //////////////////// -->
</div>
<div class="submitButton_Container">
<div class="center_Wrapper"><input type="submit" class="submit__button" value="Submit"></div>
</div>
</form>
</div>
</div>

Why python function doesn't works in the JS (using eel)

I know this issue has probably been dealt with before, however I can't find any proper workarounds to it.
I'm getting this message:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
I also get other errors sometimes, like:
GET file:///C:/eel.js net::ERR_FILE_NOT_FOUND
when I running my main.py and index.html
here's the code:
JS
"use strict";
async function sendForm() {
alert(1);
// #region Input
let InputLinkBox = document.search.link;
let LinkVal = InputLinkBox.value;
let InputNumBox = document.search.num;
let NumVal = InputNumBox.value;
let InputNameBox = document.search.name;
let NameVal = InputNameBox.value;
let InputAressBox = document.search.adress;
let AdressVal = InputAressBox.value;
let InputTINBox = document.search.tin;
let TINVal = InputTINBox.value;
let InputGearboxBox = document.search.gearbox;
let GearboxVal = InputGearboxBox.value;
let InputContactBox = document.search.contact;
let ContactVal = InputContactBox.value;
let InputEmailBox = document.search.email;
let EmailVal = InputEmailBox.value;
let InputDirectorBox = document.search.director;
let DirectorVal = InputDirectorBox.value;
let InputDateBox = document.search.date;
let DateVal = InputDateBox.value;
let InputWarehouseBox = document.search.warehouse;
let WarehouseVal = InputWarehouseBox.value;
let PackVal;
let VATVal;
// #endregion
if (document.getElementById('packyes').checked) {
PackVal = document.getElementById('packyes').value;
}
else {
PackVal = document.getElementById('packno').value;
}
if (document.getElementById('vatyes').checked) {
VATVal = document.getElementById('vatyes').value;
}
else {
VATVal = document.getElementById('vatno').value;
}
let summ = await eel.summer_py(LinkVal, NumVal)();
alert(summ);
let ReturningMassive = [NumLink, NumVal, NameVal, AdressVal, TINVal, GearboxVal, ContactVal, EmailVal, DirectorVal, DateVal, WarehouseVal, PackVal, VATVal];
return ReturningMassive;
}
document.getElementById("Btn-send").onclick = sendForm;
Python
import eel
import os
eel.init(f'{os.path.dirname(os.path.realpath(__file__))}/web')
#eel.expose
def summer_py(a, b):
return a + b
eel.start('index.html')
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My First Title</title>
<link href="style.css" rel="stylesheet">
<script type="text/javascript" src="/eel.js"></script>
</head>
<body bgcolor="#DCDCDC" text="2E2E2E">
<form name="search" action="#">
<div class="text-field">
<input class="text-field__input" type="text" name="link" id="input" autocomplete="off" placeholder="Link to the item">
<input class="text-field__input" type="text" name="num" id="input" autocomplete="off" placeholder="Number of item">
<input class="text-field__input" type="text" name="name" id="input" autocomplete="off" placeholder="Name of the company">
<input class="text-field__input" type="text" name="adress" id="input" autocomplete="off" placeholder="City, adress">
<input class="text-field__input" type="text" name="tin" id="input" autocomplete="off" placeholder="TIN(INN) of the company">
<input class="text-field__input" type="text" name="gearbox" id="input" autocomplete="off" placeholder="Gearbox(KPP) of the company">
<input class="text-field__input" type="text" name="contact" id="input" autocomplete="off" placeholder="Contact information">
<input class="text-field__input" type="text" name="email" id="input" autocomplete="off" placeholder="E-mail">
<input class="text-field__input" type="text" name="director" id="input" autocomplete="off" placeholder="Name of the director">
<input class="text-field__input" type="text" name="date" id="input" autocomplete="off" placeholder="Date">
<input class="text-field__input" type="text" name="warehouse" id="input" autocomplete="off" placeholder="Warehouse locatnion">
</div>
<fieldset>
<legend>is the cost of packaging and transport included?</legend>
<div>
<input type="radio" id="packyes" name="pack" value="true"
checked>
<label for="huey">Yes</label>
</div>
<div>
<input type="radio" id="packno" name="pack" value="false">
<label for="dewey">No</label>
</div>
</fieldset>
<fieldset>
<legend>is the cost of VAT included?</legend>
<div>
<input type="radio" id="vatyes" name="vat" value="true"
checked>
<label for="huey">Yes</label>
</div>
<div>
<input type="radio" id="vatno" name="vat" value="false">
<label for="dewey">No</label>
</div>
</fieldset>
<div class="text-field">
<button id="Btn-send" class="button blue">Send</button>
</div>
</form>
<script src="script.js"></script>
</body>
</html>
and I really confused 'cause it's looks ok...
Any help will be very appreciated in advance.

how to sum total of each input number(from clicking button)using jQuery

I am trying to get the total value of each input from the button and the total of all cannot exceed 4. However, I can only make each input not go beyond 4 and the total only sum inside each input not the sum from all the input. //sorry if my question/explanation confuses anyone cuz I don't really know how to put it into words. But the goal of the code is to not make the total guests go beyond 4.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
</head>
<body>
<div class="container-fluid Guests-S">
<div id="form">
<div class="G-title"><b>Guests</b> (Max. 4 pax for the selected facilities)</div>
<form>
<div class="G-box">
<label for="Staff" class="Guests">Park Company's Staff</label>
<div class="dec button">-</div>
<input type="text" name="qty" id="1" readonly="" value="0" placeholder="0" class="input-filed"><br>
<div class="inc button">+</div>
</div>
<div class="G-box">
<label for="Staff" class="Guests">Guest - Adults</label>
<div class="dec button">-</div>
<input type="text" name="qty" id="2" readonly="" value="0" placeholder="0" class="input-filed"><br>
<div class="inc button">+</div>
</div>
<div class="G-box">
<label for="Staff" class="Guests">Guest - Children</label>
<div class="dec button">-</div>
<input type="text" name="qty" id="3" readonly="" value="0" placeholder="0" class="input-filed"><br>
<div class="inc button">+</div>
</div>
<div class="G-box">
<label for="Staff" class="Guests">Total</label>
<input type="text" id="total" value="0" disabled=""><br>
</div>
<script>
$(document).ready(function () {
$('.dec').click(function (e) {
var form = $(this).parents('.G-box');
var inputfiled = form.find('.input-filed').val();
console.log(inputfiled);
var total = parseInt(inputfiled);
total -= 1;
if (total < 0) {
total = 0;
}
form.find('.input-filed').val(total);
$('#total').val(total);
});
$('.inc').click(function (e) {
var form = $(this).parents('.G-box');
var inputfiled = form.find('.input-filed').val();
console.log(inputfiled);
var total = parseInt(inputfiled);
total += 1;
if (total > 4) {
total = 4;
}
console.log(total);
form.find('.input-filed').val(total);
$('#total').val(total);
});
});
</script>
</form>
</div>
</div>
</body>
Use a simple function to loop through the input with name=qty
$(document).ready(function () {
$('.dec').click(function (e) {
var form = $(this).parents('.G-box');
var inputfiled = form.find('.input-filed').val();
//console.log(inputfiled);
//console.log(total);
var qty = parseInt(inputfiled);
qty = (qty <= 0) ? 0 : (qty-1); // short hand if statement
form.find('.input-filed').val(qty);
$('#total').val(get_total_qty()); // <<< Here
//}
});
$('.inc').click(function (e) {
var form = $(this).parents('.G-box');
var inputfiled = form.find('.input-filed').val();
//console.log(inputfiled);
let total = get_total_qty();
//console.log(total);
if(total < 4){
var qty = parseInt(inputfiled);
qty = (qty >= 4) ? 4 : qty+1; // short hand if statement
form.find('.input-filed').val(qty);
$('#total').val(get_total_qty()); // <<< Here
}
});
});
// function to loop through the inputs qty and get total
function get_total_qty(){
let total = 0;
$("input[name='qty']").each(function(){
total += +this.value
});
return total <= 4 ? total : 4;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form">
<div class="G-title"><b>Guests</b> (Max. 4 pax for the selected facilities)</div>
<form>
<div class="G-box">
<label for="Staff" class="Guests">Park Company's Staff</label>
<div class="dec button">-</div>
<input type="text" name="qty" id="1" readonly="" value="0" placeholder="0" class="input-filed"><br>
<div class="inc button">+</div>
</div>
<div class="G-box">
<label for="Staff" class="Guests">Guest - Adults</label>
<div class="dec button">-</div>
<input type="text" name="qty" id="2" readonly="" value="0" placeholder="0" class="input-filed"><br>
<div class="inc button">+</div>
</div>
<div class="G-box">
<label for="Staff" class="Guests">Guest - Children</label>
<div class="dec button">-</div>
<input type="text" name="qty" id="3" readonly="" value="0" placeholder="0" class="input-filed"><br>
<div class="inc button">+</div>
</div>
<div class="G-box">
<label for="Staff" class="Guests">Total</label>
<input type="text" id="total" value="0" disabled=""><br>
</div>
<script>
</script>
</form>
</div>
</div>

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

How to shift values from one div panel to other in jquery?

In a Form, there are multiple div Panels
<form>
<div class="panel1">
<input type="text" value="" name="bank0" id="bank0">
<input type="text" value="" name="shank0" id="shank0">
<input type="text" value="" name="dhank0" id="dhank0">
<input type="text" value="" name="raank0" id="raank0">
</div>
<hr>
<div class="panel2">
<input type="text" value="" name="bank1" id="bank1">
<input type="text" value="" name="shank1" id="shank1">
<input type="text" value="" name="dhank1" id="dhank1">
<input type="text" value="" name="raank1" id="raank1">
</div>
</form>
Requirement:
If user left panel1 blank and entered text to panel 2;
then we want to shift all values from panel 2 to panel 1; during final submission of form.
In real use case we have 10 such panels.
Fiddle: https://jsfiddle.net/rop5f0d6/
Try this.
var inputsValue = [];
$("button").click(function () {
$(".panel2 input").each(function () {
inputsValue.push(this.value);
});
$(".panel1 input").each(function (i, value) {
$(this).val(inputsValue[i]);
});
inputsValue = [];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="panel1">
<input type="text" value="" name="bank0" id="bank0">
<input type="text" value="" name="shank0" id="shank0">
<input type="text" value="" name="dhank0" id="dhank0">
<input type="text" value="" name="raank0" id="raank0">
</div>
<hr>
<div class="panel2">
<input type="text" value="" name="bank1" id="bank1">
<input type="text" value="" name="shank1" id="shank1">
<input type="text" value="" name="dhank1" id="dhank1">
<input type="text" value="" name="raank1" id="raank1">
</div>
<hr>
<button>Submit</button>
This will only move the data from panel 2 to panel 1 if the first panel is left blank (what I read from the requirements).
Also it wipes panel 2 data to prevent duplicate form data being posted. From your question I think this is what you are aiming for?
Here is how you can implement this functionality in jQuery:
$("button").click(function(){
var moveData = true, formvalues = [];
$(".panel1 input").each(function(e, field){
if( field.value != '' ){
moveData = false;
return false;
}
});
// only move data if first panel is blank
if( moveData ){
$(".panel2 input").each(function(){
formvalues.push( this.value );
this.value = '';
});
$(".panel1 input").each(function (i) {
this.value = formvalues[i];
});
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<div class="panel1">
<input type="text" value="" name="bank0" id="bank0">
<input type="text" value="" name="shank0" id="shank0">
<input type="text" value="" name="dhank0" id="dhank0">
<input type="text" value="" name="raank0" id="raank0">
</div>
<hr>
<div class="panel2">
<input type="text" value="" name="bank1" id="bank1">
<input type="text" value="" name="shank1" id="shank1">
<input type="text" value="" name="dhank1" id="dhank1">
<input type="text" value="" name="raank1" id="raank1">
</div>
<hr>
<button>Submit</button>
I've also written the solution in vanilla JS for your reference (possibly useful) as plain JS is more efficient in performance.
var submitBtn = document.getElementsByTagName("button")[0];
submitBtn.addEventListener("click", function(){
var moveData = true,
formvalues = [],
panel1 = document.getElementsByClassName("panel1"),
panel1Fields = panel1[0].getElementsByTagName("input"),
panel2 = document.getElementsByClassName("panel2"),
panel2Fields = panel2[0].getElementsByTagName("input");
for(var i=0; i < panel1Fields.length; i++){
if( panel1Fields[i].value != '' ){
moveData = false;
return false;
}
}
// only move data if first panel is blank
if( moveData ){
for(var i=0; i < panel2Fields.length; i++){
formvalues.push( panel2Fields[i].value );
panel2Fields[i].value = '';
}
for(var i=0; i < panel1Fields.length; i++){
panel1Fields[i].value = formvalues[i];
}
}
});
<div class="panel1">
<input type="text" value="" name="bank0" id="bank0">
<input type="text" value="" name="shank0" id="shank0">
<input type="text" value="" name="dhank0" id="dhank0">
<input type="text" value="" name="raank0" id="raank0">
</div>
<div class="panel2">
<input type="text" value="" name="bank1" id="bank1">
<input type="text" value="" name="shank1" id="shank1">
<input type="text" value="" name="dhank1" id="dhank1">
<input type="text" value="" name="raank1" id="raank1">
</div>
<button>Send</button>

Categories