I am shifting a website over to Bootstrap4. One of the pages contained a simple calculator to generate percentages based on user input. This worked fine on the old site using basic HTML with no additional framework but no longer responds to the user input.
I tried double checking against a similar real-time calculator (http://javascript-coder.com/javascript-form/javascript-calculator-script.phtml), but I can't seem to get that one to work either.
function getSupport() {
var theForm = document.forms["calculator"];
var supportV = theForm.elements["support"];
var indvSupport = 0;
if (support.value != "") {
indvSupport = parseInt(supportV.value);
}
return indvSupport;
}
function getTotal() {
var indvSupport = getSupport();
//set values
var parentV = (indvSupport * 0.535).toFixed(2);
var partnersV = (indvSupport * 0.0760).toFixed(2);
var programsV = (indvSupport * 0.06).toFixed(2);
var staffV = (indvSupport * 0.255).toFixed(2);
var adminV = (indvSupport * 0.074).toFixed(2);
//display result
document.getElementById('parent').innerHTML = "$" + parentV;
document.getElementById('partners').innerHTML = "$" + partnersV;
document.getElementById('programs').innerHTML = "$" + programsV;
document.getElementById('staff').innerHTML = "$" + staffV;
document.getElementById('admin').innerHTML = "$" + adminV;
}
<form action="" id="calculator" onsubmit="return false;">
<table align="center" style="border:none;">
<tbody>
<tr>
<td style="font-weight: bold;">Total anticipated support:</td>
<td>$ <input id="support" name="support" oninput="getTotal()" type="text" /></td>
</tr>
<tr>
<td>Parent Organization (53.5%)</td>
<td>
<div id="parent" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Supporting Partners (7.6%)</td>
<td>
<div id="partners" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Programs & Support (6.0%)</td>
<td>
<div id="programs" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Staffing (25.5%)</td>
<td>
<div id="staff" style="float: right;"> </div>
</td>
</tr>
<tr>
<td>Administration (7.4%)</td>
<td>
<div id="admin" style="float:right;"> </div>
</td>
</tr>
</tbody>
</table>
</form>
Or at https://jsfiddle.net/zimerhonzl/ub7z09oL/9/
This is a fairly basic form where the user inputs their donation and can see how it will be distributed. Upon entry in the main box the lower fields should auto populate.
The "no wrap" solution in jsfiddle fixed the issue. On the actual site it turns out there was a code error above the snippet in the common.js file preventing the functions from loading properly. Unfortunately the CMS strips out any in-line javascript so I could not post the directly code above it on the actual page. Now the common.js file is properly loading the function prior to the form.
Related
I'm making a simple cart page for a website and wanted to have cart totals update dynamically. For some reason nothing adjusts though. I also don't receive an error or any activity in the console which makes me wonder if I'm using class names improperly. It's been a long time since I've tried this so apologies for forgetting how haha. Here is my html:
<tr>
<td>
<div class="cart-info">
<img src="images/watercolor2.jpg">
<div>
<p>Watercolor Set</p>
<div class="price" data-amount="25.00">Price: $25.00</div><br>
Remove
</div>
</div>
</td>
<td><input class="quantity" type="number" value="0"></td>
<td class="total">$0.00</td>
</tr>
and js:
var quantity = document.getElementsByClassName("quantity");
Array.prototype.forEach.call(quantity, update);
function update(val, i){
val.addEventListener('input', function(){
var x = val.value;
document.getElementsByClassName('total')[i].innerHTML = "$" +
(x*document.getElementsByClassName('price')[i].getAttribute("data-amount")).toFixed(2);
});
};
I've double checked the script src is spelled properly and is posted above the tag in the html file...what am I overlooking? Is there a better approach?
This is how I'd approach it. Use querySelectorAll in concert with closest(), applying the function through an input event listener. Also, you can access the data-amount via the dataset property
const doGrandTotal = () => {
let gtotal = 0;
document.querySelectorAll('.total').forEach(t => {
gtotal += +t.innerText.replaceAll("$", "")
})
document.querySelector('#gtotal').innerText = `$${gtotal.toFixed(2)}`;
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.quantity').forEach(q => {
q.addEventListener('input', e => {
let p = +e.target.closest('tr').querySelector('[data-amount]').dataset.amount * +e.target.value;
e.target.closest('tr').querySelector('.total').innerText = `$${p.toFixed(2)}`;
doGrandTotal()
})
})
doGrandTotal()
})
<table>
<tr>
<td>
<div class="cart-info">
<img src="images/watercolor2.jpg">
<div>
<p>Watercolor Set</p>
<div class="price" data-amount="25.00">Price: $25.00</div><br>
Remove
</div>
</div>
</td>
<td><input class="quantity" type="number" value="0"></td>
<td class="total">$0.00</td>
</tr>
<tr>
<td>
<div class="cart-info">
<img src="images/watercolor2.jpg">
<div>
<p>Watercolor Set</p>
<div class="price" data-amount="25.00">Price: $25.00</div><br>
Remove
</div>
</div>
</td>
<td><input class="quantity" type="number" value="0"></td>
<td class="total">$0.00</td>
</tr>
</table>
<hr> Grand total: <span id='gtotal'></span>
I'm trying to set a random number as value for an ons-input (signup_txtCodigo), but whenever I try to push the page it just shows me the alert that I put it to check the random and stays there.
This is the page template:
<!--External user register-->
<template id="signup.html">
<ons-page id="login-page" modifier="full_bg">
<ons-toolbar modifier="transparent">
<div class="center" style="font-size:150%;color:#f0f0f0">Estacionamiento UdeG</div>
<div class="left"><ons-back-button>Volver</ons-back-button></div>
</ons-toolbar>
<div align="center">
<br><img src="https://quimicabasicacucei.files.wordpress.com/2013/02/logo-udg.png?w=316" alt="logo" height=250px><br>
<p style="color:#f0f0f0">Registrar usuario</p>
<table>
<tr>
<td style="color:#f0f0f0">Código:</td>
<td><div contenteditable><ons-input input-id="signup_txtCodigo" type="text" modifier="underbar" readonly></ons-input></div></td> //this is the input I'm trying to change
</tr>
<tr>
<td style="color:#f0f0f0">Nombre:</td>
<td><ons-input input-id="signup_txtNombre" type="text" modifier="underbar" placeholder="Nombre"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Placa:</td>
<td><ons-input input-id="signup_txtPlaca" type="text" modifier="underbar" placeholder="Ej. A1B-2C3" maxlength="7"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Teléfono:</td>
<td><ons-input input-id="signup_txtTelefono" type="text" modifier="underbar" placeholder="Teléfono" maxlength="10"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Contraseña:</td>
<td><ons-input input-id="signup_txtPassword" type="password" modifier="underbar" placeholder="Contraseña" maxlength="10"></ons-input></td>
</tr>
</table><br>
<ons-button onclick="signup()" modifier="cta">Enviar</ons-button>
<ons-button onclick="cleanSignUp()" >Limpiar</ons-button><br><br>
</div>
</ons-page>
</template>
This is the function that should asign the value to the input and push the page:
//load signup page
function externalUserPage(){
var random = Math.floor((Math.random() * 999999999) + 111111111);
alert(random);
document.getElementById("signup_txtCodigo").value = random
document.querySelector('#myNavigator').pushPage('signup.html', {data: {title: 'signup'}});
}
thank you in advance
You are using The Content Template element and you have to remove the dot in the id.
so change
<template id="signup.html">
to
<template id="signuphtml">
you can access the content of the template like this
var content = document.querySelector('template#signuphtml').content;
to access you element use document.importNode
var clone = document.importNode(content, true);
var signup_txtCodigo = clone.querySelector("[input-id='signup_txtCodigo']");
now you can fill it using The textContent property
here an illustration
//load signup page
(function externalUserPage(){
var random = Math.floor((Math.random() * 999999999) + 111111111);
alert(random);
var content = document.querySelector('template#signuphtml').content;
var clone = document.importNode(content, true);
var signup_txtCodigo = clone.querySelector("[input-id='signup_txtCodigo']");
signup_txtCodigo.innerHTML = random;
//document.getElementById("signup_txtCodigo").value = random
console.log(signup_txtCodigo); document.querySelector('#myNavigator').pushPage('signup.html', {data: {title: 'signup'}});
})();
<!--External user register-->
<template id="signuphtml">
<ons-page id="login-page" modifier="full_bg">
<ons-toolbar modifier="transparent">
<div class="center" style="font-size:150%;color:#f0f0f0">Estacionamiento UdeG</div>
<div class="left"><ons-back-button>Volver</ons-back-button></div>
</ons-toolbar>
<div align="center">
<br><img src="https://quimicabasicacucei.files.wordpress.com/2013/02/logo-udg.png?w=316" alt="logo" height=250px><br>
<p style="color:#f0f0f0">Registrar usuario</p>
<table>
<tr>
<td style="color:#f0f0f0">Código:</td>
<td><div contenteditable><ons-input input-id="signup_txtCodigo" type="text" modifier="underbar" readonly></ons-input></div></td> //this is the input I'm trying to change
</tr>
<tr>
<td style="color:#f0f0f0">Nombre:</td>
<td><ons-input input-id="signup_txtNombre" type="text" modifier="underbar" placeholder="Nombre"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Placa:</td>
<td><ons-input input-id="signup_txtPlaca" type="text" modifier="underbar" placeholder="Ej. A1B-2C3" maxlength="7"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Teléfono:</td>
<td><ons-input input-id="signup_txtTelefono" type="text" modifier="underbar" placeholder="Teléfono" maxlength="10"></ons-input></td>
</tr>
<tr>
<td style="color:#f0f0f0">Contraseña:</td>
<td><ons-input input-id="signup_txtPassword" type="password" modifier="underbar" placeholder="Contraseña" maxlength="10"></ons-input></td>
</tr>
</table><br>
<ons-button onclick="signup()" modifier="cta">Enviar</ons-button>
<ons-button onclick="cleanSignUp()" >Limpiar</ons-button><br><br>
</div>
</ons-page>
</template>
you cannot change a field marked as readonly, you should use disabled
<ons-input input-id="signup_txtCodigo" type="text" modifier="underbar" disabled></ons-input>
In order to assign value to that input please check your function if it got call or you wrote it in document.ready.
for my idea this example should be work:
$( document ).ready(function() {
var random = Math.floor((Math.random() * 999999999) + 111111111);
document.getElementById("signup_txtCodigo").value = random;
});
Reference link : Input Text value Property
Just change input-id="signup_txtCodigo" to id="signup_txtCodigo"
I did a quick google search, but from what I can gather, input-id is not a valid OnSen element attribute, therefore you cannot select it by Id by conventional JavaScript means.
I have some issues with calculating some stuff with JS and getting the right values out of the input fields (number). When I use this code it doesn't show anything. So what is wrong with my JS? Do I need to include a jQuery file?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td><input type="number" name="TotalProductionTime" placeholder=""> hours</td>
</tr>
<tr>
<td>Breaks</td>
<td><input type="number" name="Breaks" placeholder=""> minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td><input type="number" name="Malfunctions" placeholder=""> minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td><p id="test"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" name="Calculate" value="calculate">
<script>
function Calculate()
{
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
</script>
</body>
</html>
You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle
You you are trying to get elements by their ID, but you don't give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.
function Calculate() {
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td>
<input type="number" id="TotalProductionTime" placeholder="">hours</td>
</tr>
<tr>
<td>Breaks</td>
<td>
<input type="number" id="Breaks" placeholder="">minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td>
<input type="number" id="Malfunctions" placeholder="">minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td>
<p id="test"></p>
</td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
</form>
Every id must be converted to integer. Example
var Malfunctions = parseInt(document.getElementById("Malfunctions").value);
then your ready to go
With HTMLInputElement you can use property .valueAsNumber which returns a numeric property if possible:
const str = document.querySelector("input").value;
const num = document.querySelector("input").valueAsNumber;
console.log(typeof str, str, str + 2);
console.log(typeof num, num, num + 2);
<input type="number" value="40" disabled />
You've got two problems here. One obvious is that you try to get a reference to the form inputs by id, but didn't give them any (you gave them a name). To fix, either change the name attribute to an id, or use the form-specific way to reference them, e.g.:
var TotalProductionTime = document.forms.frm1.TotalProductionTime
Second problem is more vicious and has to do with the scope of execution of what you put in onclick attributes. You see, your button is named "Calculate" just like your function, and in the context of the onclick attribute, its parent form is used to resolve identifiers before the global scope. So instead of calling the function named Calculate, you're trying to call the button itself. Fix that by giving them different names, referencing window.Calculate explicitly, or much better, define your event handler in JavaScript instead of using the HTML attribute:
document.forms.frm1.Calculate.onclick=Calculate
I have Javascript loading some data and because its in a loop it ends up loading multiple times which causes lengthy wait times. I need to find how to load it only once. I researched the issue and found some code but not sure how to implement it. Here is the best link I could find about my issue:
http://blog.michaelckennedy.net/2012/10/11/preventing-javascript-files-from-loading-multiple-times/
Update: Sorry it took so long to get back. I just work Wednesday through Saturday. I was asked to give my entire code. I trimmed it down considerably.
Script I'm Loading to pull only once
jQuery(function($)
{
$('#resultA').load('DocText.html #Tablemain1');
$('#resultB').load('DocText.html #Tablemain2');
Entire Code
table class="tblrohs6" border="5" cellpadding="3" cellspacing="2">
<tr>
<td align="center">
<script type="text/javascript">
var title = document.getElementsByTagName( "title" ).item(0);
document.write('<iframe src="http://some.company.com/mfgsupt/testeng/eac/b4home/city/abistatus.asp?Bldg=City&abiID='+title.innerHTML+'&Training=no" id="abiIframe" Name="abiIframe" width="550" height="55" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" ></iframe>');
</script>
<SCRIPT SRC="file://///namp-dsk-003/cim-cam/CAM/BOI/Abi/680/Common_Files/TitleCheck.js"></SCRIPT>
</td>
</tr>
<tr>
<td bgcolor="#FFFFFF">
<!----------------StartMain Table Placement-------------------------->
<p class="revisionmain"> Text List - Assembly Build Instructions</p>
<script>
$('#resultA').load('DocText.html #Tablemain1');
$('#resultB').load('DocText.html #Tablemain2');
</script>
<p id="resultA"></p>
<!---------------Start Assembly Buttons------------------------------->
<table width="80%" border="1" align="center">
<tr>
<td colspan="10"><div align="center" class="row-column-headers-RoHS">Assembly Selection</div></td>
</tr>
<tr>
<td><div align="center"><button id="b1" onclick="showX(2)"> 178-0416-00 </button></div></td>
<td><div align="center"><button id="b2" onclick="showX(3)"> 178-0427-00 </button></div></td>
</tr>
<tr>
<td colspan="9">
<div align="center"><button onclick="location.reload();"> Refresh </button></div>
</td>
</tr>
</table>
<!-------------------End Assembly Button------------------------------->
<p id="resultB"></p>
<p id="resultC"></p>
</td>
</tr>
<!--------------------End Main Table Placement--------------------------->
<tr>
<td class="bodycell"><p class="section">Lower Level Casing </p>
<table style="visibility:visible" width="100%" border="2">
<tr>
<td colspan="3"><ol start="1">
<!----------------------------------Body After Tables------------------------------------------------>
<p id="result1"></p>
<p id="result2"></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-------------------------------------- END Body After Tables------------------------------------------>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<!--------------- Start Column Selector for button--------Input at end of this doc----------->
<script>
function showX(num) {;
<!--------------- Start Column Selector for button--------Input at end of this doc----------->
<!--------------------- Start Search Column for None------------------------>
var tab = document.getElementById('part1Table');
var l = tab.rows.length;
for ( var i = 0; i < l; i++ ) {
var tr = tab.rows[i];
var cll = tr.cells[num];
if(s = cll.innerText.indexOf('None') != -1)
{
<!---------------------- End Search Column for None------------------------->
<!---------------- Start Place Lines in Document--------------------->
jQuery(function($)
{
$('#resultA').load('DocText.html #Tablemain1');
$('#resultB').load('DocText.html #Tablemain2');
if (num==2) {
$('#resultE').load('DocText.html #0416');}
if (num==3) {
$('#resultF').load('DocText.html #0427');}
$('#result1').load('DocText.html #Line1');
$('#result2').load('DocText.html #Line2');
});
<!------------------ End Place Lines in Document----------------------->
if (i==1) /*Change this for "Line in ABI Doc" */
{ var e = document.getElementById('result1'); /*Change this for "Line Hidden" */
e.style.display = 'none';}
if (i==2) /*Change this for "Line in ABI Doc" */
{ var e = document.getElementById('result2'); /*Change this for "Line Hidden" */
e.style.display = 'none';}
}}} </script>
<!-------------------------------------Start Pull part1Table Data ---------------------------------------->
<script type="text/javascript">
jQuery(function($)
{
$('#resultZZ').load('DataTableUpdate3.html #part1Table');
});
</script>
<p id="resultZZ"></p>
<!--This is for Button Column Selector, Very Important -->
<input type="text" id="cellnum" value="0"/>
<!--This is for Button Column Selector, Very Important -->
Just to let you know, your showX(num) function on line 73 of your given code, you have a broken function that isn't going to run.
function showX(num) {;
You could set a variable and check if it is set.
Example:
if (!window.dataIsLoaded) {
// load the data
}
window.dataIsLoaded = true;
But of course it would be much better to avoid executing this part of the code in some loop. You should provide more context to understand what you're doing and why the data would be loaded in a loop.
I ended up looking closer to the code and was able to take my .loads out of the loop. Now as a result it is no longer reloading the same objects multiple times. Thank for all the input. I guess sometimes re-organizing makes all the difference.
1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.