I have a list of divs created server-side, each with a price, quantity (entered by the user) and name. I've managed to use jQuery to calculate the total of each and add those up.
What I'd like to do now is to list the name, quantity and total of each item that has a value in my textarea, on a per-row basis.
So far I've got the following (the append part of which doesn't currently work):
$(document).ready(function () {
$(".product-row input").change(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("div.product-row").each(function () {
// get the values from this row:
var $price = $('.price', this).html();
var $quantity = $('.quantity', this).val();
var $total = ($price * 1) * ($quantity * 1);
// set total for the row
$('.multTotal',this).text($total);
mult += $total;
$('#textarea',this).append($name).append($total);
});
$("#total").html(mult);
}
});
If I can get this worked out, I'm pretty sure I can work out how to add the grand total and clear the textarea each time something is changed (I'm not looking for someone to do all the work).
Any feedback as to why my textarea isn't populating would be very much appreciated.
Edit: The solution, really well explained below by braks has resulted in the following (working!) code:
$(document).ready(function () {
$(".product-row input").change(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("div.product-row").each(function () {
// get the values from this row:
var price = $('.price', this).html();
var quantity = $('.quantity', this).val();
var name = $('.name', this).html();
var total = (price * 1) * (quantity * 1);
// set total for the row
$('.multTotal',this).text(total);
mult += total;
$('#textarea').val($('#textarea').val() + ' ' + name + ' ' + total);
});
$("#total").html(mult);
}
});
$(textarea).append(txt) doesn't work like you think. When a page is loaded the text nodes inside the textarea are set the value of that form field. After that, the text nodes and the value can be disconnected. As you type in the field, the value changes, but the text nodes inside it on the DOM do not. Then you change the text nodes with the append() and the browser erases the value because it knows the text nodes inside the tag have changed.
So you want to set the value, you don't want to append. Use jQuery's val() method for this.
You have to use something like $('#textarea').val($('#textarea').val() + ' ' + $name + ' ' + $total);
Except I'm not sure why you put $ in your variables, mix up with PHP ?
Related
As the code below shows, I am appending a table with some table rows containing table data. The table data is getting appended with excel formula inside. How can I change the count variable inside td.class after it was appended in table upon click event or something similar.
I Want to update td.excel count attribute with onclick event
.append("<td class="
excel " x:num x:fmla=\"=SUM(H" + count + " *I" + count + ")
$("#example").on("click", "button", function() {
$(this).closest("tr").remove();
count--;
var i = 10;
for (i = 10; i < count; i++) {
let div1 = document.getElementsByClassName("excel");
var attribute = div1.SetAttribute(count, count);
}
}
Your problem is not clear. But what I've got from your question is that you want to dynamically append to . But you end up with excel formula getting inside it.
So, according to me when you want to insert something dynamically then you should use `` these quotes instead of '' and "". eg :-
var i = 1;
.append(`<td class="hello${i}"></td>`)
Please help. I'm looping through rows and display the items in a list. When I click a row, I need to get the row name. I think I need to get the rowid but I'm not sure how. All the below code is getting is the last row name.
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS client (name TEXT)');
tx.executeSql('SELECT * FROM client', [], function (tx, results) {
for(var x = 0; x < results.rows.length; x++) {
var $single = results.rows.item(x);
var $singleName = $single.name;
var $wrapper = $('<div class="client-row" />').appendTo('.client-list');
$wrapper.append ('<div class="client-name">' + $singleName + '</div>');
$(document).on("click", ".client-row", function(){
$(".indiv-client").show();
$(".current-client").text($singleName);
});
}
});
});
Your on function is defining the behaviour of every element with class="client-row" Therefore when you run it in the loop like this it will set every client row element to be $singleName
simply create the div as
'<div class="item" data-name="' + $singleName +'" />'
and then use .attr('data-name'); to retrieve it (oh and set the .on behaviour outside of the loop)
I have a list of divs that pull integer values from a SQL table. All of those divs are not visible unless a certain selection is made in the form. I want to create another div that sum's all visible divs at the end for the user to see their ending total.
Edit: The below code is now what I have but it totals all divs not ones that are only visible.
$("#clicky").click(function () {
var total = 0;
$('.equipmentmprice').each(function() {
total += parseFloat($(this).find('span.price').eq(0).text());
});
$('#totalamount').text('Total is: $' + total);
});
I know I can use javascript or jquery but I'm not sure really where to start.
Here is an example of one of my divs:
<div class="largeplantablefive equipmentmprice" style="display:none">
<?php
$connection = mysql_connect('localhost', 'test', 'testone');
mysql_connect('localhost', 'test', 'testone');
mysql_select_db('test');
$queryone = mysql_query("SELECT price FROM pricing WHERE value = 'plantablefive'");
$query_row = mysql_fetch_array($queryone);
echo "Plan Tables: $" . ($query_row[price]) . "<span style='color:red'><i> Price does not include cost of the physical table.</i></span>";
?>
</div>
Right now I'm thinking I will have to create another div or other tag inside the echo statement where the value equals $query_row.
You can do this with jQuery...
var divCount = $("div :visible").length;
If you need to loop through them...
$("div :visible").each(function(index) {
console.log( index + ": " + $( this ).text() );
//etc.. etc..
});
Found the answer with some searching and using multiple suggestions combining it into my own. Below is what I did and the answer. Just added the :visible into the class select.
$("#clicky").click(function () {
var total = 0;
$('.equipmentmprice:visible').each(function() {
total += parseFloat($(this).find('span.price').eq(0).text());
});
$('#totalamount').text('Total is: $' + total);
});
I want to run my function when the page first loads, and again when certain elements are clicked. Each time this function is ran I need it to update the variables, but as it sits right now it is keeping the values that it found the first time the function ran.
I tried searching for this issue and found people saying to just set it to null, or undefined. So I tried doing this by adding var price = null;, var x = null;, etc. at the end of the function. That didn't do anything. So I tried adding an if statement at the top to see if price has a value greater than 0, and then changing every variable to null if it is. This didn't change anything. Now I'm not sure if I need to just re-write the entire thing, or maybe there is some other detail that I am missing?
Thanks in advance for your help.
jQuery(document).ready(function(){
var bessie = function(){
//remove or reset value of variables for next time function runs
if(price > 0){
var qtyCode = null;
var qty = null;
var price = null;
var total = null;
var newContent = null;
};
//Pull html code for plus/minus qty selector
var qtyCode = jQuery('.qtyswitcher-qty').html();
//Get value of qty that is currently selected
var qty = jQuery('#qtyswitcher-qty').val();
//Pull the current price and change the string to a number
var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,"");
//multiply price by qty to get the total for the users current selection
var total = price * qty;
//New html that will be inserted into the page
var newContent = '<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '<div id="qty">' + qtyCode + '</div>' + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p>';
//New html being inserted
jQuery(".qtyswitcher-qty").replaceWith(newContent);
};
bessie();
jQuery('.switcher-label').click(bessie);
jQuery('#qtyswitcher-oneless').click(bessie);
jQuery('#qtyswitcher-onemore').click(bessie);
});
Moved some things around and added some new code based on Data's comments. I'm not sure I did this correctly. I had also tried it with and without the parenthesis as was mentioned below. It's still staying as $9.00 even though you can see that the .price element is changing on the page when the items are clicked.
Link to page with the html I am messing with
<script type="text/javascript">
var bessie = function(){
//Pull html code for plus/minus qty selector
var qtyCode = jQuery('.qtyswitcher-qty').html();
//Get value of qty that is currently selected
var qty = jQuery('#qtyswitcher-qty').val();
//Pull the current price and change the string to a number
var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,"");
//multiply price by qty to get the total for the users current selection
var total = price * qty;
//New html that will be inserted into the page
var newContent = '<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '<div id="qty">' + qtyCode + '</div>' + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p>';
//New html being inserted
jQuery(".qtyswitcher-qty").replaceWith(newContent);
};
bessie();
$('.switcher-label, #qtyswitcher-oneless, #qtyswitcher-onemore' ).on('dblclick click', function(e) {
bessie(e);
e.stopImmediatePropagation();
});
</script>
Found the problem now, but still working on a complete solution. The .replaceWith(); was replacing the html in a way that made it not able to display updated info. The code below is working, but the problem now is that I need to find a way replace the html each time without breaking it. The way it sits now it is adding more html to the page when an element is clicked. My code is still a bit messy.
<script type="text/javascript">
jQuery(document).ready(function() {
var bessie = function(){
//Pull html code for plus/minus qty selector
var qtyCode = jQuery('.qtyswitcher-qty').html();
//Get value of qty that is currently selected
var qty = jQuery('#qtyswitcher-qty').val();
//Pull the current price and change the string to a number
var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,"");
//multiply price by qty to get the total for the users current selection
var total = price * qty;
//New html being inserted
jQuery(".qtyswitcher-add-to-cart-box").append('<p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '<div id="qty">');
jQuery(".qtyswitcher-qty").append('</div>' + '<p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p>');
};
bessie();
jQuery('.switcher-label').click(bessie);
jQuery('.input-box').click(bessie);
jQuery('#qtyswitcher-oneless').click(bessie);
jQuery('#qtyswitcher-onemore').click(bessie);
});
</script>
It's easier to separate html from javascript, so I recommend using handlebars. You pass an object and it returns html you can then use in jQuery. Notice the html string uses back-ticks to concatenate multi-line strings.
<script>
var html = `<p class="multiply">${{price}}/ea</p>
<p class="multiply2">x</p><div id="qty">{{qtyCode}}</div>
<p class="multiply3">=</p><p class="multiply">'$'{{total}}</p>`;
function bessie(){
var obj = { 'qtyCode' : $('.qtyswitcher-qty').html(),
'qty' : $('#qtyswitcher-qty').val(),
'price' : $('.price').first().text().replace(/[^0-9\.]+/g,"") };
obj.total = obj.price * obj.qty;
var template = handlebars.compile(html),
compiled = template(obj);
$(".qtyswitcher-qty").replaceWith(compiled);
};
function addListeners(){
$('.switcher-label').click(bessie());
$('#qtyswitcher-oneless').click(bessie());
$('#qtyswitcher-onemore').click(bessie());
}
$(document).ready( addListeners(); bessie(); );
</script>
Fixed it! Used insertBefore() and insertAfter() to add the html content where I wanted it. Also added a div with the class remove me that will have .remove(); used on it each time an element is clicked.
<script type="text/javascript">
jQuery(document).ready(function() {
var bessie = function(){
//Pull html code for plus/minus qty selector
var qtyCode = jQuery('.qtyswitcher-qty').html();
//Get value of qty that is currently selected
var qty = jQuery('#qtyswitcher-qty').val();
//Pull the current price and change the string to a number
var price = jQuery('.price').first().text().replace(/[^0-9\.]+/g,"");
//multiply price by qty to get the total for the users current selection
var total = price * qty;
//New html being inserted
jQuery( '<div class="removeMe"><p class="multiply">' + '$' + price + '/ea</p>' + '<p class="multiply2">x</p>' + '</div><div id="qty">' ).insertBefore( '.qtyswitcher-qty');
jQuery( '</div>' + '<div class="removeMe"><p class="multiply3">=</p> <p class="multiply">' + '$' + total.toFixed(2) + '</p></div>' ).insertAfter( '.qtyswitcher-qty' );
};
bessie();
jQuery('.switcher-label, .input-box, #qtyswitcher-oneless, #qtyswitcher-onemore' ).click(function() {
jQuery( '.removeMe' ).remove();
bessie();
});
});
</script>
I'm making a quiz. The user decides how many questions he wants to answer.
A function then takes this number and runs a loop to make an individual question div for each question. The quiz shows a Chinese character and the user has to pick the correct translation.
My code:
var fillInQuestion = function() {
questionDivIdHTML = 'question' + questionNum;
/****************************************
How do I make this Div's ID = to questionDivIdHTML?
// Creates question div
$('#questionArea').append("<div class='questionDiv'></div>");
//$('#questionArea:last-child').attr("id", questionDivIdHTML); <-- NOT WORKING
***************************************/
// Sets up a choice bank.
var choices = [];
// choices will be chosen from this.
var tempAnswerSet = allChoices.slice(0);
//find random item in the database for the question
var thisQuestion = allQuestions[Math.floor(Math.random() * allQuestions.length)];
// add that item to choices
choices.push(thisQuestion);
// remove item from 'database' so it cannot be used in another question
allQuestions.splice(allQuestions.indexOf(thisQuestion), 1);
// remove item from tempAnswer set so it can only be one choice
tempAnswerSet.splice(tempAnswerSet.indexOf(thisQuestion), 1);
// add three more items from the database (incorrect items)
var i = 3;
for (i; i > 0; i--) {
var addChoice = tempAnswerSet[Math.floor(Math.random() * tempAnswerSet.length)];
choices.push(addChoice);
// remove the one selected each time so they cant be chosen again
tempAnswerSet.splice(tempAnswerSet.indexOf(addChoice), 1);
//console.log("choices length: " + choices.length);
}
// shuffle the array
choices.shuffle();
// fill in the div with choices.
$('#questionDivIdHTML').append("Here is an question prompt:" + thisQuestion.english + " <br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[0].hanyu</script>'></input>" + choices[0].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[1].hanyu</script>'></input> " + choices[1].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[2].hanyu</script>'></input> " + choices[2].hanyu + "<br>");
$('questionDivIdHTMLwithHash').append("<input type='radio' name='question<script>questionNum</script>Choice' value='<script>choices[3].hanyu</script>'></input> " + choices[3].hanyu + "<br>");
};
var fillOutQuiz = function() {
for (questionAmount; questionAmount > 0; questionAmount--) {
fillInQuestion();
questionNum += 1;
}
};
I've gotten this code to work, but I broke it, when trying to add the dynamic ID and loop it.
You are saying that this portion of code is not working:
$('#questionArea').append("<div class='questionDiv'></div>");
$('#questionArea:last-child').attr("id", questionDivIdHTML);
Well, it does not work because the :last-child pseudo selector is used incorrectly (see below). It should be:
$('#questionArea').append("<div class='questionDiv'></div>");
$('#questionArea > :last-child').attr("id", questionDivIdHTML);
Or better, you can rearrange your code like this:
$("<div class='questionDiv'></div>")
.attr("id", questionDivIdHTML)
.appendTo("#questionArea");
#questionArea:last-child selects an element with id = questionArea which is also the last child of its parent
#questionArea > :last-child selects the last child of an element with id = questionArea