I'm trying to use a script within CSS code in order to calculate a subtotal. Unfortunately, the JSON/XML feed does not give me the subtotal I'm looking for.
<MetaData>
<labor currency="CAD">0</labor>
<parts currency="CAD">1234</parts>
<discount currency="CAD">246.8</discount>
<tax currency="CAD">147.8332</tax>
<total currency="CAD">1135.0332</total>
</MetaData>
I want to calculate PARTS-DISCOUNT and need to parse the content of the MetaData into floats to make the calculation and then convert it to string to display it.
<script>
var subtotalbeforediscount = parseFloat(Workorder.MetaData.parts, 10);
var discounttotal = parseFloat(Workorder.MetaData.discount, 10);
var subtotalfinal = subtotalbeforediscount - discounttotal;
var subtotalfinaltxt = subtotalfinal.toString();
</script>
Of course, this script does not work because the MetaData is not parsed, only the letters are parsed.
How can I make such calculation before displaying it?
Here is the CSS section where I just want to display the result of the calculation:
<tr>
<td>Sub-total final</td>
<td id="subtotalfinal" class="amount">
{{subtotalfinaltxt|money}}
</td>
</tr>
Thanks in advance.
I guess you need to ask LightSpeedHQ for support - if no support, then JavaScript/jQuery can do this:
var WorkorderString = `<MetaData>
<labor currency="CAD">0</labor>
<parts currency="CAD">1234</parts>
<discount currency="CAD">246.8</discount>
<tax currency="CAD">147.8332</tax>
<total currency="CAD">1135.0332</total>
</MetaData>`
var oParser = new DOMParser();
var $Workorder = $(oParser.parseFromString(WorkorderString, "application/xml")).find("MetaData");
var subtotalbeforediscount = parseFloat($Workorder.find("parts").text(), 10);
var discounttotal = parseFloat($Workorder.find("discount").text(), 10);
var subtotalfinal = (subtotalbeforediscount - discounttotal).toFixed(2);
var subtotalfinaltxt = subtotalfinal.toString();
$("#subtotalfinal").text(subtotalfinaltxt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Sub-total final</td>
<td id="subtotalfinal" class="amount">
</td>
</tr>
</table>
Finally, Lightspeed was kind enough to spend some time to find the solution.
Here is the final section of the script that calculate the field. There are more conditions in this script but basically, they were able to use the metadata and perform a calculation.
<script>
document.addEventListener('DOMContentLoaded', () => {
const discount = document.querySelector('#totalsDiscountsValue');
if (discount) {
const subtotal = document.querySelector('#totalsPartsValue');
const subTotalWDiscount = Number(subtotal.innerText.replace(/\$/g, "")) +
Number(discount.innerText.replace(/\$/g, ""));
const row = discount.parentElement;
row.insertAdjacentHTML('afterend', `<tr>
<td>Sous-total avec Réductions</td>
<td>${subTotalWDiscount}</td>
</tr>`);
}
})
</script>
Hope that could help someone else.
Related
I've decided to come to the wise ones of stack overflow, in hopes of gaining some insight to my problem. I'm a newbie to javascript, and the school i'm attending has given us an assignment to create a Lucky 7's program.
The instructions are that a user places a bet, clicks play, and two dice are rolled. If the dice total is 7, $4 is added to the users bet, if not, $1 is subtracted.
Once the player reaches $0, a table showing the results is displayed. The results shown are "Starting Bet", "Total Rolls Before Going Broke", "Highest Amount Won", and "Roll count from Highest Amount Won".
So far I've got most of it working, but the results are always similar: All results are the same as the starting bet, except the highest amount won, that is always 1 less than the starting bet.
Could it have something to do with my while loop? I've tried moving things around and changing the assignment operators to += instead of bet = bet + 4, but it's always the same. Any input would be much appreciated!
function hideResults() {
document.getElementById("results").style.display = "none";
}
function play() {
var startingBet = document.getElementById("betInput").value;
var bet = startingBet;
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
var diceRoll = dice1 + dice2;
var betsArray = [];
while (bet > 0) {
if(diceRoll != 7) {
bet -= 1
} else {
bet += 4
}
betsArray.push(bet)
}
var rollCounter = betsArray.length;
var highestAmount = Math.max.apply(Math, betsArray);
var highestPosition = betsArray.indexOf(highestAmount);
var rollsFromHighest = rollCounter - highestPosition;
function showResults() {
document.getElementById("results").style.display = "inline";
document.getElementById("playButton").innerHTML = "Play Again";
document.getElementById("resultsBet").innerHTML = "$" + startingBet +".00";
document.getElementById("resultsRollCounter").innerHTML = rollCounter;
document.getElementById("resultsHighestHeld").innerHTML = "$" + highestAmount + ".00";
document.getElementById("resultsRollsFromHighest").innerHTML = rollsFromHighest;
};
showResults();
}
The HTML:
<!DOCTYPE html>
<html>
<head>
<title>Lucky Sevens</title>
<link href="css/LuckySevensStyles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/LuckySevensV1.js"></script>
</head>
<body onload="hideResults()">
<!-- BET STUFFS -->
<div id="gameDiv">
<h1>Lucky Sevens</h1>
<span>Starting Bet:<input type="number" name="Starting Bet" id="betInput" placeholder="$0.00"></span>
<br/>
<button onclick="play()" id="playButton">Play</button>
</form>
</div>
<!-- RESULT STUFFS -->
<div id="results">
<table>
<caption><h2>Results</h2></caption>
<tr>
<th>Starting Bet</th>
<th id="resultsBet"></th>
</tr>
<tr>
<td>Total Rolls Before Going Broke</td>
<td id="resultsRollCounter"></td>
</tr>
<tr>
<td>Highest Amount Won</td>
<td id="resultsHighestHeld"></td>
</tr>
<tr>
<td>Roll Count at Highest Amount Won</td>
<td id="resultsRollsFromHighest"></td>
</tr>
</table>
</div>
</body>
</html>
The VARIABLE diceRoll will not re calculate the random number. You should reassign the random numbers within the loop after you push the updated bet to the array.
If you want, you could write a function to handle this, but it's just as easy to copy and paste your lines from the dice1 & dice2 and diceRoll var instantiations into the loop after the if block
I am trying to style an HTML table row based on values in that row, but I am stuck on step 1 - styling it at all!
Here's the code I have:
<tr id="tablerow<%=j%>">
<script type="text/javascript">
document.getElementById("tablerow<%=j%>").style.backgroundColor = "red";
</script>
<%=j> is pulling a row number in from the loop that's loading the data from the Access database as it loads the table.
The table rows are not showing up as red!
Then later I am going to use some IF statements in Javascript to color the rows based on data from some of the elements:
var datecheck = new Date;
if (document.getElementById("confirmStatus<%=j%>").value=="P" && (document.getElementById("confirmYear<%=j%>").value < datecheck.getFullYear())) {
document.getElementById("tablerow<%=j%>").style.backgroundColor = "LightCoral"; }
I was able to figure it out - thanks for the help!
Have you checked your JavaScript console?
Atleast it should be document.getElementById not document.getElementByID
Your script execute too early - html not ready yet. Try
<tr id="tablerow<%=j%>">
<script type="text/javascript">
window.addEventListener('load',function(){
document.getElementByID("tablerow<%=j%>").style.backgroundColor = "red";
}
</script>
But it's ugly idea do it by js
I find it better to use custom attributes instead of string concatenation:
<tr data-dbid="<%=j%>" style="background-color:red">
<td><input class="confirmYear" /></td>
<td><input class="confirmStatus" /></td>
</tr>
Then use that when needed:
function checkRow(id) {
var _tr = document.querySelector("[data-dbid=" + id + "]"),
_confirmYear = _tr.querySelector(".confirmYear"),
_confirmStatus = _tr.querySelector(".confirmStatus");
if (_confirmYear.value === "P" && _confirmStatus.value < datecheck.getFullYear())
_tr.style.backgroundColor = "LightCoral";
}
window.addEventListener('load',function(){
[].forEach.call(
document.querySelectorAll("[data-dbid]"),
function(el) { checkRow(el.dataset["dbid"]) }
);
});
I have a id on my page that I am trying to retrieve a number from and add a value to. For instance:
<td id="qty_295518">1700</td>
var quantity = 1;
var currentQty = +(jQuery.trim($("#qty_295518").text()));
var newQty = parseInt(currentQty, 10) + quantity;
When I try and add the numbers together it come out looking like this:
17001 instead of 1701
It is just appending the 1 to the end of 1700 instead of adding it to 1700. I have tried to use parseInt, +() but to no avail. Anyone have any suggestions?
Thanks
I made a few changes from yours but they're not too different. Here's my jsfiddle, maybe it will help? I've put an alert in there to let you know that the correct value is being returned
http://jsfiddle.net/muBJd/1/
I don't know if this is the case in your actual code, but make sure that the td is wrapped in tr and table tags.
Html
<table>
<tr>
<td id="qty_295518">1700</td>
</tr>
</table>
Jquery / Javascript
var quantity = 1;
var targetQuantity = $('#qty_295518').text();
var myInteger = parseInt(targetQuantity, 10);
var addingQuantities = myInteger + quantity;
It seems that you are doing something wrong outside from jquery code, because jquery code is working fine as I wrapped the <td> inside the <tr> of <table>. something like this.
<table>
<tr>
<td id="qty_295518">1700</td>
</tr>
</table>
DEMO
Try this:
var quantity = 1;
var currentQty = +(jQuery.trim($("#qty_295518").text()));
var newQty = parseInt(currentQty, 10);
newQty += quantity;
I know there are already a few questions like this, but I just can't seem to apply any of the answers (this is my first time making anything like this at all). I currently have a page that, when a button is pushed, a random image appears (thanks to some of the great posts on here, this is actually working). My issue is, the random number has a lot of repeats prior all the images being seen. I am wanting to make it where all images are seen (in a random order) before any duplicates. This is what is in the body:
<form name="imageForm">
<table border=3>
<tr align="center">
<td>
<input onclick="displayImage();" type=button value="Click Here">
</td>
</tr>
<tr>
<td>
<img src="blank.jpg" name="canvas" />
</td>
</tr>
</table>
</form>
Here is the script:
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
}
</script>
From what I have read, the way to do this would be to add a spice, and have shown images dropped into a new array, then once the original array equals 0, then have it reset. Try as I might, I have not been able to successfully integrate that into my code :( . This is what I ended up with (which does nothing, and breaks the function entirely):
<script>
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var shownImages = []
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
document.canvas.src = imagesArray[num];
shownImages.unshift(imagesArray.splice(num,num+1));
if(images.length == 0){
images.Array = shownImages;
shownImages = [];
return shownImages[0];
}
</script>
Another method mentioned seemed to be to have a function that shuffled the images first, then displayed them in the shuffled order, then reshuffled and repeated, but I got even less far with that.
There also seems to be some question on whether the random number max should be imagesArray.length by itself, or +1 or -1. I am sure there are a number of other issues with this as well, but like I said, this is my first attempt. Any help is appreciated.
You should keep track of the numbers that you have generated, and if its a repeat then get a new number.
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>
I have a dynamic form that is generated based on javascript. Here's the relevant javascript:
function addRowToTable()
{
var tbl = document.getElementById('convention');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// right cell
var cellRight = row.insertCell(0);
var el = document.createElement('textarea');
el.rows = '2';
el.cols = '80';
el.name = 'conventionSkill' + iteration;
el.size = 40;
var el2 = document.createElement('input');
el2.type = 'hidden';
el2.name = 'conventioni_alt';
el2.value = iteration;
el2.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
cellRight.appendChild(el2);
}
function removeRowFromTable()
{
var tbl = document.getElementById('convention');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
HTML:
<table id="convention">
<tr>
<td><label>Skill Descriptions:</label></td>
</tr>
<tr>
<td>
<textarea name='convention_54' rows='2' cols='80'>
text
</textarea></td>
<td><a href='javascript:void(0)' onclick='removeRowFromTable(54);'><font size=
'+1'>-</font></a></td>
</tr>
<tr>
<td>
<textarea name='convention_55' rows='2' cols='80'>
text2
</textarea></td>
<td><a href='javascript:void(0)' onclick='removeRowFromTable(55);'><font size=
'+1'>-</font></a></td>
<td><a href='javascript:void(0)' onclick='addRowToTable();'><font size=
'+1'>+</font></a></td>
</tr>
</table>
I like the add function as it simply adds a new textarea. However, the remove button removes from the bottom of the form up. How can I make it so that removeRowFromTable removes a specific textarea? For example, if I want to delete one of the textareas in the middle, rather than the last one in the form.
Thanks for any suggestions!
In short, you'll have to find the exact textarea you want to remove (probably by ID).
However, before you go too far down this road hand-rolling ID enumeration and DOM manipulation code, you might want to look at jQuery (http://jquery.com/). jQuery handles oodles of this stuff quite easily via its selector mechanism and will save you from many of the cross-browser headaches you may have if you try to do all this DOM manipulation yourself.
You'll find a lot of questions about jQuery on SO; for example look at how easy this related- and-simple table manipulation is:
What is the best way to remove a table row with jQuery?
IMHO learning jQuery was a tremendous Javascript productivity boosts for me and my team -- it's well worth the time spent in my experience.