I have a question
I want to display the input form in the currency format, but I have a problem that the input form must be clicked first.
This is my code input HTML
<label class="col-md-12 col-sm-12 col-xs-12 padding-0">Harga Jual</label>
<div class="col-md-12 col-sm-12 col-xs-12 padding-0">
<input type="text" class="form-control currency" id="hargabarang" readonly="readonly">
</div>
My code currency
<script>
$(document).ready(function() {
$('.currency').maskMoney({prefix:'Rp. ', thousands:'.', decimal:',', precision:0});
})
My calculate
<script type="text/javascript">
$(document).ready(function(){
$("#jumlah").keyup(function(){
var jumlah = parseInt($("#jumlah").val());
var minimal_jual = $("#minimal_jual").val();
var minimal_grosir1 = $("#minimal_grosir1").val();
var minimal_grosir2 = $("#minimal_grosir2").val();
var minimal_grosir3 = $("#minimal_grosir3").val();
var harga_jual = $("#harga_jual").val();
var grosir1 = $("#grosir1").val();
var grosir2 = $("#grosir2").val();
var grosir3 = $("#grosir3").val();
var satuan_jual = $("#satuan_jual").val();
var satuan_grosir1 = $("#satuan_grosir1").val();
var satuan_grosir2 = $("#satuan_grosir2").val();
var satuan_grosir3 = $("#satuan_grosir3").val();
if (jumlah < minimal_grosir1) {
var satuan = satuan_jual;
} else if(jumlah >= minimal_grosir1 && jumlah < minimal_grosir2) {
var satuan = satuan_grosir1;
} else if(jumlah >= minimal_grosir2 && jumlah < minimal_grosir3) {
var satuan = satuan_grosir2;
} else if(jumlah >= minimal_grosir3) {
var satuan = satuan_grosir3;
};
if (jumlah < minimal_grosir1) {
var harga = harga_jual;
} else if(jumlah >= minimal_grosir1 && jumlah < minimal_grosir2) {
var harga = grosir1;
} else if(jumlah >= minimal_grosir2 && jumlah < minimal_grosir3) {
var harga = grosir2;
} else if(jumlah >= minimal_grosir3) {
var harga = grosir3;
};
var total = jumlah * harga;
$("#satuanbarang").val(satuan);
$("#hargabarang").val(harga);
$("#totalharga").val(total);
});
});
</script>
I want it to look like green, but without having to highlight it
Pplease help, thank you
Related
Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
i want asking about javascript. i develop a tax calculation system.
function countsisa(){
var iv = document.getElementById("invoicevalue");
var ppn = document.getElementById("ppn");
var pph = document.getElementById("pph");
var dpp = document.getElementById("dpp");
var propv = document.getElementById("propertyvalue");
var shipv = document.getElementById("shippingvalue");
var dppship = document.getElementById("dppshipping");
var pph23 = document.getElementById("pph23");
var total = document.getElementById("total");
var income = document.getElementById("income");
var ppndoc = document.getElementById("ppndoc");
var pphdoc = document.getElementById("pphdoc");
var pphdoc23 = document.getElementById("pphdoc23");
if(iv.value.replace(/[.*+?^${}()|[\]\\]/g,"") > 0){
document.getElementById("propertyvalue").disabled = true;
document.getElementById("shippingvalue").disabled = true;
document.getElementById("dppshipping").disabled = true;
document.getElementById("pph23").disabled = true;
dpp.value = Math.ceil(iv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
pph.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.015);
ppn.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.10);
income.value = iv.value.replace(/[.*+?^${}()|[\]\\]/g,"")-pph.value-ppn.value;
}else{
if(propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") > 0){
document.getElementById("invoicevalue").disabled = true;
total = parseFloat(propv.value.replace(/[.*+?^${}()|[\]\\]/g,""),10)+parseFloat(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,""),10);
// total = String(total);
propv.value = String(propv.value);
shipv.value = String(shipv.value);
dpp.value = Math.ceil(propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
dppship.value = Math.ceil(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
pph.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.015);
pph23.value = Math.ceil(dppship.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.02);
ppn.value = (propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") - dpp.value)+(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,"")-dppship.value);
income.value = total-pph.value-ppn.value-pph23.value;
}else{
document.getElementById("propertyvalue").disabled = false;
document.getElementById("shippingvalue").disabled = false;
document.getElementById("dppshipping").disabled = false;
document.getElementById("pph23").disabled = false;
}
}
console.log(total);
if(dpp.value <= 0){
dpp.value = 0;
}
if(dppship.value <= 0){
dppship.value = 0;
}
if(pph.value <= 0){
pph.value = 0;
}
if(pph23.value <= 0){
pph23.value = 0;
}
if(ppn.value <= 0){
ppn.value = 0;
}
if(income.value <= 0){
income.value = 0;
}
dppship.value = tandaPemisahTitik(dppship.value);
dpp.value = tandaPemisahTitik(dpp.value);
pph.value = tandaPemisahTitik(pph.value);
pph23.value = tandaPemisahTitik(pph23.value);
ppn.value = tandaPemisahTitik(ppn.value);
pphdoc.value = tandaPemisahTitik(pph.value.replace(/[.*+?^${}()|[\]\\]/g,""));
pphdoc23.value = tandaPemisahTitik(pph23.value.replace(/[.*+?^${}()|[\]\\]/g,""));
ppndoc.value = tandaPemisahTitik(ppn.value);
income.value = tandaPemisahTitik(income.value);
}
this my javascript code to count value and display it in input value.
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="ppn"><?php print _('mi_invoice_ppn'); ?></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon" style="border-radius:0px;">Rp</span>
<input type="text" name="ppn" id="ppn" class="form-control" onkeydown="return numbersonly(this, event);" onkeyup="javascript:tandaPemisahTitik(this);" placeholder="0" />
</div>
</div>
</div>
this is the input code. i want change input text value has been count in javascript function. i want to manually changed again. so javascript function to count automatic. and can edit again if miscalculation.
If you want to recalculate when any input value's changed, you can add change listener on the input elements.
will be look like:
let inputElems = document.querySelectorAll("input");
for (let i = 0, len = inputElems.length; i < len; i++) {
inputElems[i].addEventListener("change", countsisa);
}
Hey everyone reading this!
I am trying to validate a form and have that text field showing in case something's left empty. It does show indeed but too many time and I can't figure out why the counter doesn't work. Open to any ideas ... Thanks!
// For checking if the fields are filled and creating an html element
var newP = document.createElement("p");
var alertText = document.createTextNode("You should fill both fields!");
newP.appendChild(alertText);
var counter = 0;
// Declaring the canvas
var canvas = document.getElementById("draw");
var ctx = canvas.getContext('2d');
var formValue = document.getElementById("gameForm");
var submit = document.querySelector("#submitGameForm");
submit.addEventListener('click', function(e){ e.preventDefault(); validateForm();});
//global machen
function validateForm(){
var name = document.getElementById("name").value;
var hours = document.getElementById("hours").value;
var expressionName = new RegExp("^[a-zA-Z\s]+$");
var expressionHours = new RegExp("[0-9 ]+");
var correct = true;
var showMessage = false;
//Test if empty
if(name == "" || name == null || hours == "" || hours == null){
showMessage= true;
correct= false;
}
if(showMessage && counter == 0){
formValue.appendChild(newP);
console.log(newP);
counter++;
}
if(!expressionName.test(name)) {
document.getElementById("name").style.background='#8e3733';
correct = false;
}
else{
document.getElementById("name").style.background='#FFFFFF';
}
if(!expressionHours.test(hours)) {
document.getElementById("hours").style.background='#8e3733';
correct = false;
}
else{
document.getElementById("hours").style.background='#FFFFFF';
}
}
<main class="game" id="mainIndex">
<div class= "divGameForm">
<h2>Confess in order to play</h2>
<form id="gameForm">
<label for="name">Enter your name:</label>
<input id="name" type="text" >
<label for="hours">How many hours per day do you spend playing?</label>
<input id="hours" type="text" >
<p>Press the button if you would like to increase them!</p>
<input id="submitGameForm" type="submit" value="Submit" >
</form>
</div>
<div class="divGame">
<canvas id="draw"> </canvas>
<div>
<p>You can only draw circles. The dimentions are 240 (width) and 300 (height). Try it out!s</p>
<label for="xPos">Enter value for x: </label>
<input id="xPos" type="text">
You can use the counter In the test scenario empty as counter++ then should change showmessage and counter > 0
var newP = document.createElement("p");
var alertText = document.createTextNode("You should fill both fields!");
newP.appendChild(alertText);
var counter = 0;
// Declaring the canvas
var canvas = document.getElementById("draw");
var ctx = canvas.getContext('2d');
var formValue = document.getElementById("gameForm");
var submit = document.querySelector("#submitGameForm");
submit.addEventListener('click', function(e) {
e.preventDefault();
validateForm();
});
//global machen
function validateForm() {
var name = document.getElementById("name").value;
var hours = document.getElementById("hours").value;
var expressionName = new RegExp("^[a-zA-Z\s]+$");
var expressionHours = new RegExp("[0-9 ]+");
var correct = true;
var showMessage = false;
//Test if empty
if (name == "" || name == null || hours == "" || hours == null) {
showMessage = true;
correct = false;
counter++;
}
if (showMessage && counter > 0) {
formValue.appendChild(newP);
console.log(newP);
}
if (!expressionName.test(name)) {
document.getElementById("name").style.background = '#8e3733';
correct = false;
} else {
document.getElementById("name").style.background = '#FFFFFF';
}
if (!expressionHours.test(hours)) {
document.getElementById("hours").style.background = '#8e3733';
correct = false;
} else {
document.getElementById("hours").style.background = '#FFFFFF';
}
}
The country is changing along side the shipping. I could alert my shipping but will refuse to display in my div. What could be wrong? All calculations working well and displays well except for the #usashipping please help. My country changes and give the correct value for the calculation. The shipping fee just will not display.
<!-- language: lang-js -->
<script type="application/javascript">
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
$('.add').click(function() {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput= currentValue + 1;
$('#gems').val(newinput);
(newinput);
if(newinput==1)
{
var np1=(19.99*2.0);
flpay= np1.toFixed(2);
$('#flpay').html(flpay);
var tot= (fees + shipping + flpay);
var total= tot.toFixed(2);
$('#total').html(total);
var newp=19.99;
var price= newp.toFixed(2);
$('#price').html(price);
useprice= 19.99;
}
else if(newinput>1)
{
//useprice=useprice;
var newprice= 19.99 + (9.99*(newinput-1));
var np1 =(2*newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot =( fees + shipping + (2*newprice) );
var total= tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp= newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
First & Last Months Payment = $<span data-first-last-month-fees="" id="flpay"></span>
</div>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
<div>
Total due today : $<span data-total-due="" id="total"></span>
</div>
Your code should work perfectly, but there are few things that you could improve in your code:
Instead of declaring shipping variable 3 times in each condition, you need to declare it only once, then update it in each condition, and make sure it's stored as a string so it can be displayed correctly in your HTML.
Instead of updating the HTML content of your span in every condition, just update it with the shipping amount in the end.
This is how should be your code:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
Demo:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="country">
<option value="40">40</option>
<option value="236">236</option>
<option value="100">100</option>
</select>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
I can see error showing in your code. I found "$('.add').click" inside "$('#country').change". Also "$('#country').change" function you declared local variable "var shipping;" that's why no change on global "shipping;" value but you using it inside "$('#country').change" function. I modified little bit now try with following code and comment reply if not work for you:
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
})
$('.add').click(function () {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput = currentValue + 1;
$('#gems').val(newinput);
(newinput);
if (newinput == 1) {
var np1 = (19.99 * 2.0);
flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + flpay);
var total = tot.toFixed(2);
$('#total').html(total);
var newp = 19.99;
var price = newp.toFixed(2);
$('#price').html(price);
useprice = 19.99;
}
else if (newinput > 1) {
//useprice=useprice;
var newprice = 19.99 + (9.99 * (newinput - 1));
var np1 = (2 * newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + (2 * newprice));
var total = tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp = newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
})
I only changed the div id from #usashipping to something else and it works just fine. Maybe #usashippingis now a constant in jquery library.
Currently when a button is clicked, it subtracts an inputted value. I want to have a preset value subtracted once a preset button is clicked. It would also be perferable that I could reuse a function later on a different button with different values like so:
var preset = function(val1, val2, val3, val4) {
//function to subtract from current values
}
$('presetButton').click(function(){
preset(1,2,3,4)
}
Here is the current function as I have it. The first button function works, but I wanted to copy it into a preset button with preset values. The function would not include $(this) because the button would not be in the same wrapper div and are not siblings.
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
$('#presets').click(function(){
//set up the subtracting and current variables
var subCal = 120;
var subPro = 24;
var subCarbs = 3;
var subFat = 1;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFat = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal)
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
//Add to presets to history
})
});
The HTML
<h1>Track your Macros</h1>
<div class="wrapper">
<div id="calories">
<div class="number"><p>1945</p></div>
<div class="label"><p>Calories</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="protein">
<div class="number"><p>200</p></div>
<div class="label"><p>Protein</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="carbs">
<div class="number"><p>173</p></div>
<div class="label"><p>Carbs</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="fats">
<div class="number"><p>50</p></div>
<div class="label"><p>Fats</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
</div>
<div id="presets"><img src="on-logo.png"></div>
Try
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
var preset = function(val1, val2, val3, val4) {
//set up the subtracting and current variables
var subCal = val1;
var subPro = val2;
var subCarbs = val3;
var subFat = val4;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFats = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal);
}
//apply new values
var applyHistory = function(id, val) {
$(id + ' .history').append("<p>" + val + "</p>");
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
applyHistory('#calories', subCal);
applyHistory('#protein', subPro);
applyHistory('#carbs', subCarbs);
applyHistory('#fats', subFat);
}
$('#presets').click(function(){
preset(120,24,3,1);
})
});
Demo: Fiddle