How do I compare the value - javascript

When I click on the buttons successfully added, how do I add the value to previous value when the button is clicked more than once.
$(document).ready(function() {
$('.btn').click(function() {
var btn = $(this);
var count = btn.data("count");
var name = btn.data("name");
var price = btn.data("price")
console.log(name + price)
$('.display').append('<h2>' + name + '</h2> ' + count + ' pc. price = ' + price)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="Buterbrod" data-price="140" data-count="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<div class="display"></div>

Just create the container to hold the expected value from the start, but fill it's price and number with zeroes. Then when the buttons are clicked just add those number.
Edit 1: If you have too many products for this, just dynamically add those 'zero container' with 'if not exist' logic
Edit 2: It is recommended to represent each product with an ID. The ID may be database primary key, slug, or anything that doesn't contain space or is numeric.
$( document ).ready(function() {
//$('.container_product').css('display','none');
$('.btn').click(function(){
var btn = $(this);
var count = btn.data("count");
var identifier = btn.data("identifier");
var name = btn.data("name");
var price = btn.data("price")
//console.log(name + price)
//$('.display').append('<h2>'+ name + '</h2> ' + count + ' pc. price = ' + price)
if($("#container_"+identifier).length == 0) { // if not exist
$(".display").append(`
<span id="container_`+identifier+`" class="container_product">
<h2>`+name+`</h2>
<span id="num_`+identifier+`">0</span> pc.
price = <span id="price_`+identifier+`">0</span>
</span>
`)
}
$("#container_"+identifier).css('display','block');
$("#price_"+identifier).html( parseInt($("#price_"+identifier).html())+price );
$("#num_"+identifier).html( parseInt($("#num_"+identifier).html())+1 );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="buterbrod" data-price="140" data-count="1" data-identifier="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" data-identifier="2" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<button data-name="double buterbrod" data-price="9999" data-count="1" data-identifier="3" class="btn" type='submit'>
<p>double buterbrod</p>
<p class="price">9999</p>
</button>
<div class="display">
</div>

It can easily be done using your code, append the content in a container a give that a class, next time just check if that container already exist then insert the html into that. Plus you also need to keep updating the count variable.
$(document).ready(function() {
$('.btn').click(function() {
var btn = $(this);
var data = btn.data();
var count = data.count;
var name = data.name;
var price = data.price * count;
data.count = count + 1;
var html = '<h2>' + name + '</h2> ' + count + ' pc. price = ' + price;
name = name.split(" ").join("_");
if($('.display').find("."+name).length)
$('.display').find("."+name).html(html);
else
$('.display').append($("<div class='"+name+"'></div>").html(html));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="Buterbrod" data-price="140" data-count="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<div class="display"></div>

Find the appended element first into the 'display' element, if its length is 0 then directly append it, else first get the value of data-price attribute and add your updated price to it.
$(document).ready(function() {
$('.btn').click(function() {
var btn = $(this);
var count = Number(btn.data("count"));
var name = btn.data("name");
var price = Number(btn.data("price"));
var $h2 = $("<h2></h2>")
.attr('data-name', name)
.attr('data-count', count)
.attr('data-price', price)
.text(name + ' ' + count + ' pc. price = ' + price);
var dataNameSelector = '*[data-name=' + name + ']';
var childrenOrders = $('.display').find(dataNameSelector);
if (childrenOrders.length === 0) {
$('.display').append($h2);
} else {
var updatedPrice = Number(childrenOrders.data('price')) + price;
var updatedCount = Number(childrenOrders.data('count')) + count;
childrenOrders.data('price', updatedPrice);
childrenOrders.data('count', updatedCount);
childrenOrders.text(name + ' ' + updatedCount + ' pc. price = ' + updatedPrice);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-name="Buterbrod" data-price="140" data-count="1" class="btn" type='submit'>
<p>Buterbrod</p>
<p class="price">140</p>
</button>
<button data-name="hotdog" data-price="110" data-count="1" class="btn" type='submit'>
<p>hotdog</p>
<p class="price">110</p>
</button>
<div class="display"></div>

Related

Trying to get the HTML displayed to change every time a new button is clicked with jquery

let table = 6;
let i = 1;
$(function() {
let $newOperatorButton = $('button');
$newOperatorButton.on('click', function math(){
let msgOperator = '';
let expression;
let operator = $(this).attr("value");
if(operator === '+'){
msgOperator = ' + ';
expression = (table + i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table + i) + '<br />';
i++;
}
} else if (operator === '-') {
msgOperator = ' - ';
expression = (table - i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table - i) + '<br />';
i++;
}
some code missing but it adds multiplication and division
let el = document.getElementById('blackboard');
el.innerHTML = msg;
}
);
});
This code is inside the body tag in my index.html
<section id="page">
<section id="blackboard"></section>
</section>
<form id="operator">
<button name="add" type="button" value="+">+</button>
<button name="subtract" type="button" value="-">-</button>
<button name="multiply" type="button" value="x">x</button>
<button name="division" type="button" value="/">/</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/index.js"></script>
I have it so it prints out a table with 10 numbers depending on the button clicked. For ex. table = 6 and i = 1 is 6+1=7.... 6+10=16
You need an if statement at the end that reset your equations and variables.
after you've run your equation "i" is still equal to 11 so it never passes into the while loops again, you also need to empty your message so it doesn't keep adding addition text to your existing text.
$("#blackboard").html(msg)
if (i == 11) {
i = 1
msg = ""
}

simple addition within array

When the user clicks the button to show all values in the array, how can I get it to add up the total of all 'amounts due'? For example, if one user enters $5, another enters $10 and another enters $25, the total would be displayed as $40.
// Code goes here
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
</body>
</html>
I have changed your code as per your requirement as shown below.Hopefully it will solve your problem
// Code goes here
var customerarray = [];
function displaydata() {
var total=0;
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue+"<br/>";
total+=parseInt(customerarray[i].AmountDue);
}
document.getElementById('output').innerHTML ="User Input Data <br/>" +innerTemphtml;
document.getElementById('total').innerHTML = "Grand Total = "+total;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
<p id="total"></p>
</body>
</html>
There are mutliple things you have to look. I have added a display due() for you.
And here is my js fiddle https://jsfiddle.net/jinspeter/1qxo50uz/
You have to user a number field for Amount. And also addding the amount has to parsed to Int to reject string.
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="number" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<button onClick="displayTotalDue()" class="button" type = "button"> Display Due</button>
<p id="output"></p>
</body>
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function displayTotalDue(){
var total =0;
customerarray.forEach(function(item){
total = total + item.AmountDue
});
var innerTemphtml = 'totalDue=' + total;
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: parseInt(document.getElementById('Amount').value)
});
console.log(customerarray);
}
I try to fix your code. To make it more easy to read. I put the displaydata() method inside of the addtoarray() method, so you can see the results after adding an element in the customers array. Also, I replaced the for with a forEach and added a new div for the total.
I create a node that is a p tag, which will contain the name, id and amount. This tag then will be added to the outputLabel for each element in the array. You can optimize this by just adding the additional node and not running the entire array to print the output.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata() {
outputLabel.innerHTML = '<p>Customers</p>';;
total = 0;
customers.forEach(function(customer) {
var node = document.createElement('p');
node.innerHTML = customer.customerName + ', ' +
customer.customerID + ', ' +
customer.AmountDue;
total += parseInt(customer.AmountDue);
outputLabel.appendChild(node);
});
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
customers.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
displaydata();
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Optimized version: for this version I moved the node (p tag) to the addtoarray() method and I capture the data from the inputs. Then I calculate the total. With this two values a call the displaydata(). This method save time running the array each time you want to print the added element.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata(node, total) {
outputLabel.appendChild(node);
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
var customerName = document.getElementById('custName').value;
var customerID = document.getElementById('CustID').value;
var amountDue = document.getElementById('Amount').value;
customers.push({
customerName: customerName,
customerID: customerID,
amountDue: amountDue
});
var node = document.createElement('p');
node.innerHTML = customerName + ', ' + customerID + ', ' + amountDue;
total += parseInt(amountDue);
displaydata(node, total);
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Set "AmountDue" property of object to number instead of string at .push() call
Number(document.getElementById('Amount').value)
use Array.prototype.reduce() to add two elements of array at a time, return sum
let dues = customerarray.reduce((a, {AmountDue:b}) => a + b, 0);

How to insert text into one textarea out of several with id?

I have two textareas with different ids which both have wysiwyg buttons for text formatting. I can insert the formatting tags into the first textarea however when I try to insert tags into the second textarea, the tags are inserted into the first one. Obviously when I use the buttons assigned to their respective textarea I would like the format tags to be inserted in the appropriate textarea. In jQuery I try to store the id of the buttons to concatenated with '#textarea' to recreate the textarea id.
<button class="B" id="11">B</button>
<button class="I" id="11">I</button>
<button class="U" id="11">U</button>
<button class="S" id="11">S</button>
<div id="textarea1" class="textareaWrapper">
<textarea id="textarea11" class="textarea"></textarea>
</div>
<button class="B" id="22">B</button>
<button class="I" id="22">I</button>
<button class="U" id="22">U</button>
<button class="S" id="22">S</button>
<div id="textarea2" class="textareaWrapper">
<textarea id="textarea22" class="textarea"></textarea>
</div>
<script>
$(document).ready(function () {
$('button.B').click(function () {
var id = $('button.B').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + id);
})
$('button.I').click(function () {
var id = $('button.I').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<i></i>");
})
$('button.U').click(function () {
var id = $('button.U').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<u></u>");
})
$('button.S').click(function () {
var id = $('button.S').attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<s></s>");
})
})
</script>
The problem is that inside your click handler you're getting a ref to the first button's id.
try this: $(this).attr('id');
Like:
$(document).ready(function () {
$('button.B').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + id);
})
$('button.I').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<i></i>");
})
$('button.U').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<u></u>");
})
$('button.S').click(function () {
var id = $(this).attr('id');
$('#textarea' + id).val($('#textarea' + id).val() + "<s></s>");
})
})
You must not use same ids for multiple controls.
My suggestion is to use dummy attribute e.g.'data-group', which can be used in JavaScript and browser simply ignores it. Like:
<button class="B" data-group="1">B</button>
<button class="I" data-group="1">I</button>
<button class="U" data-group="1">U</button>
<button class="S" data-group="1">S</button>
<div id="textarea1" class="textareaWrapper">
<textarea id="textarea11" class="textarea"></textarea>
</div>
<button class="B" data-group="2">B</button>
<button class="I" data-group="2">I</button>
<button class="U" data-group="2">U</button>
<button class="S" data-group="2">S</button>
<div id="textarea2" class="textareaWrapper">
<textarea id="textarea22" class="textarea"></textarea>
</div>
<script>
$(document).ready(function () {
$('button.B').click(function () {
var grp = $('button.B').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + id);
})
$('button.I').click(function () {
var grp = $('button.I').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + "<i></i>");
})
$('button.U').click(function () {
var grp = $('button.U').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + "<u></u>");
})
$('button.S').click(function () {
var grp = $('button.S').attr('data-group');
$('#textarea' + grp).val($('#textarea' + grp).val() + "<s></s>");
})
})
</script>
Hope it works.
The problem is the way you retrieve your ids:
$('button.S').attr('id');
This will get the id of the first element passing the selector. Consider this JSFiddle.

userHow to collect the values from html form for variable input values in google app script?

I am creating the input fields with the add more feature which are then sent to the google script file, how can I collect the values of the fields as shown in code I implemented below..
google app script file
code.gs
function getFormValue(formValue) {
var myarr= {};
var count = formValue.count;
for(var g = 1; g<=count; g++ )
{
user["I"+g] = formValue.user+g; // error, what to do here
}
// code
}
index.html
<script>
$(document).ready(function() {
var counter = 2;
$("#addMoreUser").click(function() {
if (counter > 7) {
alert("Only 7 Users are allowed");
return false;
}
var newRowDiv = $(document.createElement('div'))
.attr("id", 'rowDiv' + counter);
newRowDiv.after().html('<div class="row" id="rowDiv" ><div class="col-md-3"><input class="form-control" placeholder="user'+ counter +' " name="user'+ counter +'" id="user'+ counter +'" type="text" value=""></div></div>');
newRowDiv.appendTo("#rowDivGroup");
$("#count").val(counter);
counter++;
});
$( "#submitForm" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
console.log(ret);
}).getFormValue(this); //"this" is the form element
});
});
</script
<form class="contact-form" id="myform">
<input type="hidden" value="1" name="count" id="count">
<div id="rowDivGroup">
<div class="row" id="rowDiv">
<div class="col-md-3">
<input class="form-control" placeholder="Name of User" name="user1" id="user1" type="text" value=""></div></div></div>
<a class="btn btn-sm btn-flat btn-success btn-rounded" id="addMoreUser">Add More Users</a>
<input type="submit" class="btn btn-flat flat-color btn-rounded btn-sm" id="submitForm" value="Submit Details ">
</form>
This code takes the value of an array, and creates an object:
function getFormValue(formValue) {
formValue = ["someInput1", "someInput2", "someInput3", "someInput4", "someInput5", "someInput6", "someInput7"];
Logger.log('formValue: ' + formValue);
var myarr= {};
var count = formValue.length;
Logger.log('count: ' + count);
var user = {};
for(var g = 1; g<=count; g++ )
{
Logger.log('g: ' + g);
var k = "user"+g;
var userID = "I" + g;
Logger.log("userID: " + userID);
Logger.log("formValue: " + formValue[g-1]);
user[userID] = formValue[g-1];
Logger.log("The property value: " + user[userID]);
}
}
I've run the code, and it works. The values for the array are hard coded for testing purposes.

Javascript Specificity (Only Respond to Clicked Item)

I'm very new to Javascript and am looking for a way to have my code only respond to the clicked item in the list. (full JSFiddle here: http://jsfiddle.net/5cjPF/, although for some reason buttons aren't responsive...)
For the functions below, each applies only to a certain clicked item, however, right now only the first item that each refers to is responding. A friend of mine suggesting creating a class for each function, but I honestly have no idea where to begin and would really appreciate a push in the right direction!
<script type="text/javascript">
var submitcount = 0;
function arrow() {
if (submitcount == 0 || submitcount % 2 == 0) {
var extension = document.getElementById('one');
extension.insertAdjacentHTML('beforeend', '<div id="before-two"><div id="two"><div class="btn-group"><!----><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>synonyms</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button><!----></div><div class="btn-group"><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>beast</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button></div><p><div class="btn-group"><!----><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>antonyms</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button><!----></div><div class="btn-group"><button type="button" class="left" onclick="modify_qtyTag(1)"></button><!----><button type="button" class="tag" id=tag>gentle</button><!----><button type="button" class="right" onclick="modify_qtyTag(0)"></button></div></p></div></div></div>');
}
else if(document.getElementById('two')) {
var deleted = document.getElementById('before-two');
deleted.remove(deleted.selectedIndex);
}
submitcount += 1;
};
var upvotes = 0;
var votes = 0;
function modify_qty(val) {
var qty = document.getElementById('qty').value;
votes += 1;
upvotes += val;
var percent = Math.round((upvotes / votes) * 100);
document.getElementById('qty').value = percent;
}
var upvotesTag = 0;
var votesTag = 0;
function modify_qtyTag(val) {
var extension = document.getElementById('tag');
votes += 1;
upvotes += val;
var percent = Math.round((upvotes / votes) * 100);
var allThings = percent + "%," + " 100%," + " 100%," + " 100%;";
extension.style.backgroundSize = allThings;
extension.style.backgroundSize = "100%";
extension.style.backgroundSize = percent + "%, 100%, 100%, 100%";
}
</script>
The JS should be:
function modify_qtyTag(val, tagid) {
var extension = document.getElementById(tagid);
var votes = parseInt(extension.getAttribute("data-votes"), 10) + 1;
var upvotes = parseInt(extension.getAttribute("data-upvotes"), 10) + val;
var percent = Math.round((upvotes / votes) * 100);
var allThings = percent + "%," + " 100%," + " 100%," + " 100%;";
extension.style.backgroundSize = allThings;
extension.setAttribute('data-votes', votes);
extension.setAttribute('data-upvotes', upvotes);
}
The HTML would be something like:
<button type="button" class="left" onclick="modify_qtyTag(1, 'tag1')"></button>
<button type="button" class="tag" id="tag1" data-votes="0" data-upvotes="0">synonyms</button>
This adds an argument to the function that tells it which tag to update. And instead of using global variables for the votes and upvotes, it stores it in data attributes in the tag element, so that each one can have its own percentage.

Categories

Resources