I am trying to highlight a value in a div that is the lowest value in an array.
When the user completes each input row (design outlet and actual outlet) the outletIndex() function is called which calculates the percentage and pushes the value into an array. This part I have working.
Then what I am trying to do is find the lowest number in that array and highlight the div (proportion). I want this to be dynamic so as the user completes each input row the percentage is calculated and the lowest index value is highlighted progressively.
I am using querySelectorAll() to match the div class value to the lowest index value but Im not sure if I need to parse a nodeList to match the value of the indexArray?
I am also wondering that if a mistake is typed into the fields and added to the Index array and it happens to be the lowest index it wont match the index values that are shown on the HTML and not call the function.
document.querySelector('#outlet_actual_1').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_1").valueAsNumber || 0;
let design = document.getElementById("outlet_design_1").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage").textContent = `${result1.toFixed(1)}%`;
}
}
});
document.querySelector('#outlet_actual_2').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_2").valueAsNumber || 0;
let design = document.getElementById("outlet_design_2").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage2").textContent = `${result1.toFixed(1)}%`;
}
}
});
document.querySelector('#outlet_actual_3').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_3").valueAsNumber || 0;
let design = document.getElementById("outlet_design_3").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage3").textContent = `${result1.toFixed(1)}%`;
}
}
});
const indexArray = [];
function outletIndex(a, b) {
let result = a / b * 100;
if (!isNaN(result)) {
indexArray.push(+result.toFixed(2));
indexFindandHighlight();
}
console.log(indexArray, result);
return result;
}
function indexFindandHighlight(){
const lowestIndex = Math.min(...indexArray);
const indexCheck = document.querySelectorAll('.proportion').valueAsNumber || 0;
console.log(lowestIndex);
if (lowestIndex == indexCheck) {
$(document).ready(function() {
$("#outlet_actual_1", "#outlet_actual_2", "#outlet_actual_3").onchange(function(){
$(".proportion").effect( "highlight", {color:"#669966"}, 3000 );
});
});
}
};
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
onkeydown="outletIndex();"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
onkeydown="outletIndex();"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage">
</div>
</td>
</div>
</tr>
<tr>
<div class="form-group row 2" id="outlets2">
<td>
<input
name="outlet_design"
class="form-control design_2"
id="outlet_design_2"
type="number"
placeholder="Outlet 2 Design"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_2"
id="outlet_actual_2"
type="number"
placeholder="Outlet 2 Actual"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_2"
type="number"
placeholder="Outlet 2 Balance"
/>
</td><td>
<div class="proportion" id="percentage2">
</div>
</td>
</div></tr>
<tr>
<div class="form-group row 3" id="outlets3">
<td>
<input
name="outlet_design"
class="form-control design_3"
id="outlet_design_3"
type="number"
placeholder="Outlet 3 Design"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_3"
id="outlet_actual_3"
type="number"
placeholder="Outlet 3 Actual"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_3"
type="number"
placeholder="Outlet 3 Balance"
/>
</td><td>
<div class="proportion" id="percentage3">
</div>
</td>
</div></tr>
</div>
</table>
</fieldset>
</form>
</div>
Multiple issues:
Clean up HTML
Reuse code
Consistency, Either use jquery or javascript
Separate UI changes from data change.
Consistency, Bind event listener either using HTML or javascript file.
Please check below sample
const number = (str) => Number(str) || 0;
const bind = (id) => {
function onBind(e) {
let actual = number(document.querySelector(`#outlet_actual_${id}`).value);
let design = number(document.querySelector(`#outlet_design_${id}`).value);
let result1 = percentage(actual, design);
if (!isNaN(result1)) {
document.querySelector(
`#percentage_${id}`
).textContent = `${result1.toFixed(1)}%`;
}
updateIndex(id, result1);
highlight();
}
document
.querySelector(`#outlet_actual_${id}`)
.addEventListener("change", onBind);
document
.querySelector(`#outlet_design_${id}`)
.addEventListener("change", onBind);
};
function percentage(a, b) {
return b === 0 ? 0 : (a / b) * 100;
}
let percentages = [];
function updateIndex(id, value) {
percentages[id - 1] = value;
}
function highlight() {
let minIndex = -1;
let minValue = Number.MAX_SAFE_INTEGER;
for (let index in percentages) {
if (percentages[index] < minValue) {
minIndex = Number(index);
minValue = percentages[index];
}
}
if (minIndex === -1) return;
document.querySelector(`#percentage_${minIndex + 1}`).style.color = "red";
setTimeout(() => {
document.querySelector(`#percentage_${minIndex + 1}`).style.color = "black";
}, 3000);
}
bind(1);
bind(2);
bind(3);
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage_1">
</div>
</td>
</div>
</tr>
<tr>
<div class="form-group row 2" id="outlets2">
<td>
<input
name="outlet_design"
class="form-control design_2"
id="outlet_design_2"
type="number"
placeholder="Outlet 2 Design"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_2"
id="outlet_actual_2"
type="number"
placeholder="Outlet 2 Actual"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_2"
type="number"
placeholder="Outlet 2 Balance"
/>
</td><td>
<div class="proportion" id="percentage_2">
</div>
</td>
</div></tr>
<tr>
<div class="form-group row 3" id="outlets3">
<td>
<input
name="outlet_design"
class="form-control design_3"
id="outlet_design_3"
type="number"
placeholder="Outlet 3 Design"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_3"
id="outlet_actual_3"
type="number"
placeholder="Outlet 3 Actual"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_3"
type="number"
placeholder="Outlet 3 Balance"
/>
</td><td>
<div class="proportion" id="percentage_3">
</div>
</td>
</div></tr>
</div>
</table>
</fieldset>
</form>
</div>
Related
I want to build a increase-able data upload document,
currently the HTML like this
function getData() {
let newArr = [];
var room = {};
var time = {};
var prod = {};
var quan = {};
var room = $('.room').each(function() {
room.push($(this).val());
});
var time = $('.time').each(function() {
time.push($(this).val());
});
var prod = $('.prod').each(function() {
prod.push($(this).val());
});
var quan = $('.quan').each(function() {
quan.push($(this).val());
});
newArr.push({
room,
time,
prod,
quan,
});
console.log(newArr)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="insert">
<input type="text" name="room[]" class="room">
<input type="text" name="time[]" class="time">
<input type="text" name="prod[]" class="prod">
<input type="text" name="quan[]" class="quan">
</div>
<div class="insert">
<input type="text" name="room[]" class="room">
<input type="text" name="time[]" class="time">
<input type="text" name="prod[]" class="prod">
<input type="text" name="quan[]" class="quan">
</div>
<div>
<button name="btnSubmit" onclick="getData()">Click</button>
</div>
hope to get date kind of the following structure
Array
[
Object1 => {
"room":"string/number", "time":"string/number", "prod":"string/number", "quan":"string/number"
}
Object2 => {
"room":"string/number", "time":"string/number", "prod":"string/number", "quan":"string/number"
}
]
then the error tells me either can not user .push() on object,
or it just keep getting undefined;
after I check some articles but seems the solution as set up formData()
JavaScript loop over input creates an array of objects
which I already had a formData() and contains file need to upload.
or some of them would be using .map() function alter into another array.
which makes me trying to merge multiple array into one or like below solutions,
now I'm figuring those answers but not very match yet
combine multiple array elements into single object in javascript1
convert array of objects into object of objects properties from array
at this current point, hope someone could've help me.
for the increase-able explain :
after few change now use jQuery prepend/append an object, the second form has been changed to table, first form stays as file-upload.
$('#theTable').prepend(`
<tr class="insert">
<td><input type="text" name="room[]" class="room"></td>
<td><input type="text" name="time[]" class="room"></td>
<td><input type="text" name="prod[]" class="room"></td>
<td><input type="text" name="quan[]" class="room"></td>
</tr>
`);
Native javascript (which not using but work)
function addInputField() {
// table
const table = document.getElementById('theTable');
// row
let newRow = table.insertRow(-1);
newRow.innerHTML += `
<td><input type="text" name="room[]" class="room"></td>
<td><input type="text" name="time[]" class="time"></td>
<td><input type="text" name="prod[]" class="prod"></td>
<td><input type="text" name="quan[]" class="quan"></td>
`;
newRow.className = 'insert';
table.prepend(newRow);
}
You are getting the error because you're trying to push a value to an object. push is for pushing values to arrays not objects.
Try this
function getData() {
let newArr = [];
$('.insert').each(function(){
newArr.push({
room: $(this).find('[name="room[]"]').val(),
time: $(this).find('[name="time[]"]').val(),
prod: $(this).find('[name="prod[]"]').val(),
quan: $(this).find('[name="quan[]"]').val(),
})
})
console.log(newArr)
return newArr
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="insert">
<input type="text" name="room[]" class="room">
<input type="text" name="time[]" class="time">
<input type="text" name="prod[]" class="prod">
<input type="text" name="quan[]" class="quan">
</div>
<div class="insert">
<input type="text" name="room[]" class="room">
<input type="text" name="time[]" class="time">
<input type="text" name="prod[]" class="prod">
<input type="text" name="quan[]" class="quan">
</div>
<div>
<button name="btnSubmit" onclick="getData()">Click</button>
</div>
I have been working on this fiddle:
https://jsfiddle.net/j1vrb7to/165/
The code in that fiddle is this:
HTML:
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /><br /><br />
<input type="numbers" id="new-tuition-total" disabled="disabled" /><br /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /><br /><br />
<input type="numbers" id="new-state-total" disabled="disabled" />
</div>
JavaScript:
const NewTuitionInputs = document.querySelectorAll("div#CalculationContainer > input.new-tuition");
const NewStateInputs = document.querySelectorAll("div#CalculationContainer > input.new-state");
NewTuitionInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewTuitionInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-tuition-total").value = total;
}
});
NewStateInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewStateInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-state-total").value = total;
}
});
As the users enter values into the textboxes, I want to update the value of another field to display running totals. Ultimately I will need to keep track of 20+ running totals on my form. Instead of maintaining 20+ functions, is it possible to use a single function to calculate running totals on the fly? Here is some pseudocode to demonstrate what I'm thinking:
var ThisInput = document.querySelectorAll("div#CalculationContainer > input.[INPUT_CLASS_PARAMETER_HERE]");
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("[DYNAMICALLY_CHOOSE_WHERE_TO_DISPLAY").value = total;
}
});
You have a convention that the inputs have a class and then the total has an id with that class name plus -total. You can use this to your advantage in making a general purpose function:
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
Usage would then be:
trackTotals("new-tuition");
trackTotals("new-state");
// whatever else that follows same conventions
Live example follows:
trackTotals("new-tuition");
trackTotals("new-state");
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/><br/><br/>
<input type="numbers" id="new-tuition-total" disabled="disabled"/><br /><br />
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/><br/><br/>
<input type="numbers" id="new-state-total" disabled="disabled"/>
</div>
Yes, you can create a function that takes the id:
function doTotal(name) {
var ThisInput = document.querySelectorAll(`div#CalculationContainer > input.${name}`);
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById(`${name}-total`).value = total;
}
});
}
Note that I'm using string templates to build the selector strings.
You can use the event delegation method:
const calcContainer = document.getElementById('CalculationContainer')
, sumElms =
{ tuition: { sum: document.getElementById('new-tuition-total'), elms: [...document.querySelectorAll('input.new-tuition')] }
, state: { sum: document.getElementById('new-state-total'), elms: [...document.querySelectorAll('input.new-state')] }
}
;
calcContainer.oninput= ({target}) =>
{
if (!target.matches('.new-tuition, .new-state')) return
let sumElm = target.matches('.new-tuition') ? sumElms.tuition : sumElms.state
sumElm.sum.value = sumElm.elms.reduce((s,e)=>s+e.valueAsNumber,0)
}
#CalculationContainer input {
float: left;
clear:both;
width: 5em;
}
#CalculationContainer input:disabled {
margin-bottom: 1em;
font-weight: bold;
color:black;
}
<div id="CalculationContainer">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" id="new-tuition-total" disabled="disabled" value="0">
<input type="number" class="form-control new-state" value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" id="new-state-total" disabled="disabled"value="0">
</div>
How do I sum the two highest values from a list of inputs using JavaScript?
I've tried the below, but I get 4 instead of 5:
<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>
<td>
<script type="text/javascript">
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var len = tdsCompulsory.length;
var cDatax = [];
var cData = cDatax.reverse();
sum = 0;
for(var i = 0; i < 2; i++){
cData.push(tdsCompulsory[i].value);
sum += +tdsCompulsory[i].value;
}
alert (sum);
</script>
</td>
</tr>
</table>
First you find the two highest values, and then sum them together. I'd probably do it something like this:
document.getElementById("the-button").onclick = function() {
// Get the values as numbers
var values = Array.prototype.map.call(
document.getElementsByClassName('compulsory1'),
function(input) {
return +input.value; // + converts to number
}
);
// Put them in order *highest* to *lowest*
values.sort(function(left, right) {
return right - left;
});
// Add the first two
var result = values[0] + values[1];
console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">
More about that Array.prototype.map.call thing in this answer about looping through arrays and array-like things.
But if you specifically want to use reverse, you'd do that after the sort:
document.getElementById("the-button").onclick = function() {
// Get the values as numbers
var values = Array.prototype.map.call(
document.getElementsByClassName('compulsory1'),
function(input) {
return +input.value; // + converts to number
}
);
// Put them in order lowest to highest
values.sort(function(left, right) {
return left - right;
});
// Then reverse that
values.reverse();
// Add the first two
var result = values[0] + values[1];
console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">
You could try something like following:
function PickTwoHighestCtrl() {
let els = document.querySelectorAll(".compulsory1");
let values = Array.prototype.map.call(els, (el) => {
return Number(el.value) || 0;
});
let highest = Math.max.apply(Math, values);
let secondHighest = Math.max.apply(
Math, values.filter(e => e !== highest)
);
console.log("Two highest values are:", highest, secondHighest, "and their sum is", highest + secondHighest)
}
document.addEventListener("DOMContentLoaded", PickTwoHighestCtrl);
<input class="compulsory1" type="text" value="1" />
<input class="compulsory1" type="text" value="3" />
<input class="compulsory1" type="text" value="2" />
Check this fiddle
<html>
<head>
<script>
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var cDatax = [];
sum = 0;
for(var i = 0; i < 3; i++){
cDatax.push(tdsCompulsory[i].value);
}
// let's convert it to a real array of numbers, not of strings :
var intArray = cDatax.map(Number);
var max = Math.max.apply(null, intArray);
// now let's sort it and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
var sum = max+second;
alert(sum)
</script>
</head>
<body>
<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>
<td>
</td>
</tr>
</table>
</body>
</html>
You can try something like this:
Steps
Get all elements
Get their values. Note, since you expect values to be number, yuo should parse them as well.
Sort value array in descending order instead of .sort + .reverse
Calculate your sum
Sample
// Get all elements
var tdsCompulsory = document.getElementsByClassName('compulsory1');
// Get values from all elements
var valArr = Array.prototype.map.call(tdsCompulsory, function(el) {
return parseInt(el.value)
});
// Sort value array in descending order
var cDatax = valArr.sort(function(a, b) {
return b-a
});
var sum = cDatax[0] + cDatax[1];
console.log(sum)
<table id="tableID">
<tr>
<td>
<input name="name" class="compulsory1" type="text" value="1" />
</td>
<td>
<input name="name1" class="compulsory1" type="text" value="3" />
</td>
<td>
<input name="name2" class="compulsory1" type="text" value="2" />
</td>
</tr>
</table>
var tdsCompulsory = document.getElementsByClassName('compulsory1'),
cDatax = Array.prototype.map.call(tdsCompulsory, function(el) {
return parseInt(el.value) || 0;
}),
sum = 0;
cDatax
.sort(function(a, b){
return a - b;
})
.reverse();
sum = cDatax[0] + cDatax[1];
console.log(sum);
<table id="tableID">
<tr>
<td><input name="name" class="compulsory1" type="text" value="1" /></td>
<td><input name="name1" class="compulsory1" type="text" value="3" /></td>
<td><input name="name2" class="compulsory1" type="text" value="2" /></td>
</tr>
</table>
Trying to calculate a selection value from a radio group and values from other fields. Any 'Name' input adds a value to the Total. I need the value from the radio group to be added to that total.
Here is the HTML:
<FORM NAME="testauthorization" ACTION="" METHOD=POST id="exhibitreg">
<table>
<tr>
<td><label>
<input type="radio" name="sponsorship" value="3000" id="sponsor1" />
$3,000</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1500" id="sponsor2" />
$1,500</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1000" id="sponsor3" />
$1,000</label>
<br /></td>
</tr>
<tr>
<td>Name 1 <INPUT NAME="Name_1" TYPE="TEXT" id="name1" onchange="updatecost(1, 50)" onkeyup="updatecost(1, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_1" TYPE="TEXT" VALUE="" size="4" id="cost1"></td>
</tr>
<tr>
<td>Name 2<INPUT NAME="Name_2" TYPE="TEXT" id="name2" onchange="updatecost(2, 50)" onkeyup="updatecost(2, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_2" TYPE="TEXT" VALUE="" size="4" id="cost2"></td>
</tr>
<tr>
<td>Name 3<INPUT NAME="Name_3" TYPE="TEXT" id="name3" onchange="updatecost(3, 50)" onkeyup="updatecost(3, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_3" TYPE="TEXT" VALUE="" size="4" id="cost3"></td>
</tr>
<tr>
<td colspan="4">Total:
<INPUT NAME="Total" id="Total" TYPE="TEXT" VALUE="" size="8" onFocus="this.form.elements[0].focus()" >
<INPUT TYPE="HIDDEN" onchange="totalcost()" onkeyup="totalcost()"></td>
</tr>
</table>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<input type="RESET" name="Reset" value="Reset" />
</FORM>
And here is the JS:
<script language="JavaScript" type="text/javascript">
function getRadioValue(name) {
var group = document.getElementsByName('sponsorship');
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.getElementById("cost" + num);
if (!text) return;
if (!cost) return;
if (text.value == "") {
cost.value = "";
}
else {
cost.value = dollars;
}
totalcost();
}
function totalcost() {
var total = 0;
for (var i = 1; i <= 3; i++) {
var cost = document.getElementById("cost" + i);
if (cost.value) total += Number(cost.value);
}
document.getElementById("Total").value = total;
}
//-->
</script>
What am I missing? By the way, in case it is not clear, I am a JS novice, so I fully accept criticism that helps me understand a more fundamental error in my approach. Simple is best for me: ;-) Thank you in advance.
Change below function in place of existing
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.querySelector('input[name="sponsorship"]:checked');
if (!text) return;
if (!cost) return;
totalcost(cost);
}
function totalcost(cost) {
var total = 0;
for (var i = 1; i <= 3; i++) {
var text1 = document.getElementById("name" + i);
if (text1.value != "") total += Number(cost.value);
}
document.getElementById("Total").value = total;
}
I was wondering if there was a way I could ask if a certain button was pushed so that it would do a certain thing in the function. I know I could split this up into two separate functions, but I want to know how to do this this way.
I'll put my code below.
function displaySort(form) {
var list = form.values.value.replace(/\s+/g, '')
list = list.split(/,/)
if (document.getElementById("fSort").form.input.id) {
list.sort()
var listAsString = list.join(", ")
form.sortedDisplay.value = listAsString
} else if (document.getElementById("rSort").form.input.id) {
list.sort(reverseCompare)
var listAsString = list.join(", ")
form.reverseSortedDisplay.value = listAsString
}
window.alert("Messed Up");
}
function reverseCompare(s1, s2) {
if (s1 < s2) {
return +1
} else if ( s1 == s2 ){
return 0
} else {
return -1
}
}
the form:
<form>
<table>
<tr>
<td>
<input type="text" name="values" value=" Bob, Ted, Carol,
Bette, Alice, Peter "
onclick="if (this.value == this.defaultValue) this.value=''"
size="80"
/>
<input type="button"
onclick="displaySort(this.form)"
value="Sort"
id="fSort"
/>
<input type="button"
onclick="displaySort(this.form)"
value="Reverse Sort"
id="rSort"
/>
<input type="reset"
value="Reset Form"
/>
</td>
</tr>
<tr>
<td>
<input type="text" name="sortedDisplay" value="Sorted list will show here"
size="35"
readonly
style="font-size:24pt;font-weight:normal;"
/>
</td>
</tr>
<tr>
<td>
<input type="text" name="reverseSortedDisplay"
value="Reverse sorted list will show here"
size="35"
readonly
style="font-size:24pt;font-weight:normal;"
/>
</td>
</tr>
</table>
</form>
Add another parameter to the function button:
function displaySort(form, button)
{ ...
And pass the button reference to it when clicked:
<input type="button"
onclick="displaySort(this.form, this)"
value="Reverse Sort"
id="rSort"
/>