Javascript Discount Calculation for each item - javascript

I have an existing document that has pre existing pricing. So on the page I have a bunch of elements for example price here with each one having different pricing of course.
How can I write a jquery/javascript script to take each of those prices and divide them by 24 and then append a p tag that shows that calculation, this should happen on page load.
so far i have this, just testing it on click but it gives me the same answer for each, which is the very first occurrence of the price divided by 24.
for ex if they price is 1600, or 500, or 100000 the answer it gives me is always based on 1600.
$(".button").click(function () {
var value = $('.price').text();
var price = parseFloat(value)/24;
$('.price').append('<p>' + price + '</p>');
});
Can someone help please?
Thank you :)

In the above code, your use of the text() method selects only the first element with the class price.
You need to loop over all the elements with the class price.
$(".button").click(function () {
$('.price').each(function(index, el) {
var price = parseFloat($(el).text())/24;
$(el).append('<p>' + price + '</p>');
});
});

This is because of var value = $('.price').text(); it selects the first price it finds.
You should use a variable in the event handler to get access to the item that was clicked on. Then get the price from that.
Assuming the button has a descendant with a price class :
$(".button").click(function (e) {
var value = $(event.currenttarget).find(".price")
...
}

I think something like the following implementation should work:
document.querySelectorAll('.button').forEach(element => {
const priceElement = element.querySelector('.price');
const price = parseFloat(priceElement.textContent) / 24;
const childElement = document.createElement('p');
childElement.textContent = price;
priceElement.appendChild(childElement);
});

$(".button").click(function () {
$('.price').each(function(p){
$('.price')[p].innerHTML = $('.price')[p].innerHTML/24});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='price button'>240</div>
<div class='price'>480</div>

Related

Dynamically generated form

I have simple Database, which contains fields like ID, product_name, product_description, image, cost.
I have a dynamically generated form which I'm going to send using jQuery, what should I change in my JavaScript to pass to defined div the data which I got from my DB via PHP?
JavaScript Code:
$(function() {
var number = 1;
var contentToLoad = 'Defined structure';
$('a.add').click(function(e) {
e.preventDefault();
$('#calc').append(contentToLoad);
number++;
});
$('#calc').on('click', 'a.design_button', function(e) {
e.preventDefault();
$(this).parent().remove();
});
});
---
UPDATE:
I need a little help with merging two parts of JavaScripts to make it work. I need to put somehow that part:
var number = 1;
var contentToLoad = 'Defined structure';
$('a.add').click(function(e) {
e.preventDefault();
$('#calc').append(contentToLoad);
number++;
});
where a.add i've replaced with submit button, inside this one
function add(data_array){
$(document).on('submit', '#add', function()
{
var r_data = data_array;
alert(r_data);
...
});
}
but I can't make it work ;/
I've menaged to do sth like that:
function mini(data_array){
var number = 1;
var r_arr = data_array;
$(this).on('submit', function(e) {
e.preventDefault();
var contentToLoad = '<div id="item-'+ number +'" class="item row"> '+ number +' '+r_arr+' Defined structure </div>';
$('#calc').append(contentToLoad);
number++;
});
}
But now I have a problem with making it work correctly, because it adds me the correct div + all divs which was previously added.
Let's just say that I have blank site and I want to add two divs, so I click twice on the button and it should add me two divs, but it adds after 1st click div with id = 1 and after 2nd click div with id = 2 + div with id=1, So in effect I have three divs after two clicks.
Where in code placed above I've made mistake ?

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

Using On Blur to Call a Function

I am trying to have a web page update a value when the text field loses focus. I have tried a number of different suggested variations for the onblur event but nothing seems to work as expected. Currently I have the onblur in the html code on line 59
<input name="qty1" id="qty1" size="8" value="0" onBlur="productCost()" />
and I have tried to make the correction in the script as well.
function productCosts()
{
var totalMap = document.getElementById("qty1").onblur();
totalMap.value = ("qty1") * ("price1");
//$("#cost1").html (totalMap.toFixed(2));
alert(totalMap)
//var totalPlanner = ('qty2') * ('price2');
//var totalHiker = ('qty3') * ('price3');
}
I have created a fiddle to show the entire program. http://jsfiddle.net/Jn6LQ/ Any help would be really greatly appreciated.
It's easy with jQuery
$('#qty1').bind('blur', productCosts)
or with JS
document.getElementById('qty1').addEventListener('blur', productCosts)
Note: In the below, $ is not jQuery, the OP is using it as a shortcut for getElementById.
The line
totalMap.value = ("qty1") * ("price1");
multiplies the string "qty1" with the string "price1". Perhaps you meant to look up the elements, and then get their values:
totalMap.value = $("qty1").value * $("price1").value;
Separately, using onXyz attributes is usually not best practice. Instead:
$("qty1").onblur = productCosts;
$("price1").onblur = productCosts;
function productCosts() {
var value = $("qty1").value * $("price1").value;
$("cost1").innerHTML = value.toFixed(2);
}
(There I'm assuming the price can be changed as well, but that may not be the case on your page.)
Looking at the fiddle, though, you have a much bigger problem: You want to do that for multiple lines. Using id values to do that is going to make for gainly, over-large code. Instead, use a class on each input, and then relate it to the other inputs in the row using the fact they're all in the same row.
function productCosts() {
var row = this.parentNode.parentNode,
qty = row.querySelector(".qty"),
price = row.querySelector(".price"),
cost = row.querySelector(".cost"),
value = qty.value * price.value;
cost.innerHTML = value.toFixed(2);
}
var list, i;
list = document.querySelectorAll(".qty, .price");
for (i = 0; i < list.length; ++i) {
list[i].onblur = productCosts;
}
jQuery.blur() looks like what you're looking for:
$('#qty1').blur(function(){
alert('here');
});

jQuery traversing and finding textboxes

If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark
Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()
Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});
You could use $(this).closest('input')
Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});

jQuery. Select all elements with a class but without style="display:none;" attribute

I have the following class, which selects what's inside of the td.lineitemtotal cells and uses it in the getTotal function to get a total of the cells. But, I don't want the function to use the lines that are in a tr.line_item_row with style="display:none;" attribute.
$(document).ready(function() {
var line = $('.item');
// so the line totals are calculated on page load
getLineItemTotals(line);
var line_totals = $('.lineitemtotal');
getTotal(line_totals); // So the total is calculated on page load.
});
// get invoce grand total
function getTotal(lines) {
var total = 0;
$.each(lines, function(){
total += parseFloat($(this).html());
});
$('#total-price').html('$' + total.toFixed(2));
}
Do you want this ?
$('.lineitemtotal:visible');
This set contains the not hidden elements having class lineitemtotal.
var line_totals = $('.lineitemtotal:not([style*="display:none"])');
On your selector include the :visible selector:
$('.lineitemtotal:visible');
If you know for certain that the attribute will always be style="display:none;" you can use an attribute selector.
Instead of this:
var line = $('.item');
Try this:
var line = $('.item[style!="display:none;"]');
using [attribute="value"] looks for elements that have attribute with value value, adding the ! before the = looks for things that do NOT match.

Categories

Resources