jQuery/JavaScript adding a number to a value retrieved from.text() - javascript

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;

Related

How to show table rows based on URL parameter

Currently the page is accessed using a link, for instance help.html?show=charInPw.
The table is written in the following manner:
<table>
...
<tbody class="table-body">
<tr class="pwLen"><td colspan="5" class="subheading">Password Length</td></tr>
<tr class="pwLen"><td class="first">Minimum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="pwLen"><td class="first">Maximum length</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td colspan="5" class="subheading">Characters in Password</td></tr>
<tr class="charInPw"><td class="first">Minimum numeric characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
<tr class="charInPw"><td class="first">Minimum alphabetic characters</td><td>Y</td><td> </td><td>Y</td><td>Y</td></tr>
...
The CSS is as follows:
table tbody tr{
text-align: center;
display: none;
}
(There are also trs in thead and they are always shown by default.)
Then I have some Javascript code as follows (jQuery is not an option):
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
for (i = 0; i < document.getElementsByClassName(c); i++)
document.getElementsByClassName(c)[i].style.display='table-row';
</script>
However I am not able to get my rows to show.
How should I change the code on the page to show only the rows referenced by the show parameter?
Edit #1: As a test I did the following hard-coding but it didn't work too!
<script>
var url = new URL(window.location.href);
var c = url.searchParams.get("show");
var trs = document.getElementsByClassName('pwLen');
for (i = 0; i < trs.length; i++)
trs[i].style.display='table-row';
</script>
Edit #2: I have combined two solutions below into one - please see https://jsfiddle.net/tea45p2o/. The demo output shown is what I want, however I am not able to see that when I save the file and open the page in my browser. What is going on?
With much help from BJohn and MrJ, I have come up with my solution as follows:
<script>
function show() {
var url = new URL(window.location.href);
var c = '.' + url.searchParams.get("show");
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
}
</script>
Then, I changed my <body> to
<body onLoad="show();">
Use below code:
for (let el of document.querySelectorAll(c)) el.style.display = 'table-row';
You also need to append dot (.) with class name, which you are getting from the URL.
Please find the fiddle here
ŷou are missing to place .length
for (i = 0; i < document.getElementsByClassName(c).length; i++)
But I think it would be more readable on this way
for(let TR_x of [... document.getElementsByClassName(c) ]) {
TR_x.style.display='table-row';
}
but I definitely prefer
document.querySelectorAll('.'+c).forEach(trX=>{ trX.style.display='table-row' })

Perform simple calculations in javascript within CSS

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.

Styling HTML with Javascript based on values

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"]) }
);
});

How to delete specific textarea field?

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.

img SRC from first cell in a row with jquery

i have a table such that each row is like this
<tr>
<td><input/> <img id="foo" src="redMinus.png"/></td>
some more tds
<td> <a onclick="wow('foo',$(this))"></a>
</tr>
I want to find out if the img in the first td has an src that contains "redMinus"
This is what I have but it doesnt seem to be working?
function wow(id, item){
var tr$ = item.parentNode.parentNode;
var details = tr$.find('img[src*="redMinus"]');
}
Any ideas?
Thanks!
You're mixing jQuery with DOM elements.
Change your code to
var details = item.closest("tr").find('img[src*="redMinus"]');
Your parameter is given the name item within your function, but you are trying to use a variable with the name item$ instead. Either rename the parameter or use the correct parameter name in the function.
var same = "redMinus" == $(this).parent('td').prev().children('img').attr('src').substring(0,7);
function wow(id, item){
var src = $('#' + id).attr('src');
var srcIndex = src.indexOf('redMinus');
if(srcIndex >= 0)
// redMinus is present in the string
else
// redMinus is not present in the string
}

Categories