We have set of checkbox which is identified as date checkbox. These are known as check-in date. Check-out is 1 greater then check-in date. For example if check-in date is 24/09/2017 then checkout is 25/09/2017.
So We are trying to get short date range if continuous date selected, For example, if we have four date 24/09/2017,25/09/2017,26/09/2017,27/09/2017. If we select 24/09/2017 then check-in date is 24/09/2017 and checkout is 25/09/2017. But if we select 24 and 25,26 then in array we have three values
checkindat:"24/09/2017",checkouts:"25/09/2017"
and
checkindat:"25/09/2017",checkouts:"26/09/2017"
and
checkindat:"26/09/2017",checkouts:"27/09/2017"
so we want if date range in sequence then it would show check-in date as 24/0/2017 and checkout date as 27/09/2017. But if we un-check date then it would work as its working now.
here is some part of my code in this jsfiddle
var alreadycheckin = [];
$("input[class='check htcheck']:checkbox").change(function() {
var roomids = $(this).attr("roomid");
checkindat = $(this).attr("name");
var new_dates = moment(checkindat, "DD.MM.YYYY");
var checkid = new_dates.format('DD-MM-YYYY');
//if ($(this).is(":checked"))
{
var html = '';
arr = [];
var roomcods = $(this).attr("value");
var roomids = $(this).attr("roomid");
checkindat = $(this).attr("name");
var new_dates = moment(checkindat, "DD.MM.YYYY");
var checkid = new_dates.format('DD-MM-YYYY');
//console.log(checkid);
var checkouts = new_dates.add(1, 'days').format('DD/MM/YYYY');
var roomcodes = $(this).attr("value");
var uniq = roomids + '_' + name + '_' + checkindat;
uniq = uniq.split("/").join("").split("_").join("");
var uniqs = '';
//console.log($("#aa"+roomids));
// alreadycheckin.push({ roomids : roomids, checkindat : checkindat, checkouts: checkouts });
var arrElement = {
roomids: roomids,
checkindat: checkindat,
checkouts: checkouts
};
if ($(this).is(":checked")) {
//alreadycheckin[uniq]={ roomids : roomids, checkindat : checkindat, checkouts: checkouts };
alreadycheckin.push(arrElement);
} else {
var index1 = arr.indexOf(arrElement);
alreadycheckin.splice(index1, 1);
}
var tmpAlreadycheckin = [];
// tmpAlreadycheckin=alreadycheckin.slice(0);
for (var i = 0; i < alreadycheckin.length; i++) {
if (i > 0) {
if (typeof alreadycheckin[i - 1] != "undefined" || alreadycheckin[i - 1] != null) {
if (alreadycheckin[i].checkouts == alreadycheckin[i - 1].checkindat) {
console.log("111");
var arrElement1 = {
roomids: roomids,
checkindat: alreadycheckin[i].checkindat,
checkouts: alreadycheckin[i - 1].checkouts
};
tmpAlreadycheckin.push(arrElement1);
//tmpAlreadycheckin[i].checkouts =tmpAlreadycheckin[i+1].checkouts;
//tmpAlreadycheckin.splice(i+1, 1);
} else {
console.log("2222");
var arrElement2 = {
roomids: roomids,
checkindat: alreadycheckin[i].checkindat,
checkouts: alreadycheckin[i].checkouts
};
tmpAlreadycheckin.push(arrElement2);
}
} else {
console.log("3333");
var arrElement2 = {
roomids: roomids,
checkindat: alreadycheckin[i].checkindat,
checkouts: alreadycheckin[i].checkouts
};
tmpAlreadycheckin.push(arrElement2);
}
} else {
console.log("3333");
var arrElement2 = {
roomids: roomids,
checkindat: alreadycheckin[i].checkindat,
checkouts: alreadycheckin[i].checkouts
};
tmpAlreadycheckin.push(arrElement2);
}
}
console.log(tmpAlreadycheckin);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input roomid="15" id="15_24/09/2017" class="check htcheck" name="24/09/2017" value="1" type="checkbox">24/09/2017 <br/>
<input roomid="15" id="15_25/09/2017" class="check htcheck" name="25/09/2017" value="1" type="checkbox">25/09/2017 <br/>
<input roomid="15" id="15_26/09/2017" class="check htcheck" name="26/09/2017" value="1" type="checkbox">26/09/2017 <br/>
<input roomid="15" id="15_27/09/2017" class="check htcheck" name="27/09/2017" value="1" type="checkbox">27/09/2017 <br/>
If you have an array of objects in this format: [{checkindat:"24/09/2017",checkouts:"25/09/2017"},{checkindat:"25/09/2017",checkouts:"26/09/2017"}] :then you could first sort the array by checkindate, and then iterate over the array backwards. You would start on the last element, look at its checkindat, then compare it to the previous element's checkouts. If they're the same, update the previous elements checkouts to the one ahead of it, and then delete the one ahead of it.
Related
I have written a simple javascript function that takes the input of a date textfield and convert it to dd-mm-yyyy format.
function dateConvert(dateValue) {
if(dateValue == null) {
var grDate = null;
}
else {
var n = dateValue.search("/");
if( n >= 0) {
var res = dateValue.split("/");
var day = res[0];
if( day.length == 1 ) {
day = "0"+day;
}
var month = res[1];
if( month.length == 1 ) {
month = "0"+month;
}
var year = res[2];
var grDate = day+"-"+month+"-"+year;
/*alert(grDate);*/
}
else {
var grDate = dateValue;
}
}
document.getElementById("mydate").value = grDate;
}
<input type="text" name="mydate" id="mydate" onblur="dateConvert(this.value)" />
Is there a way to make function "global" and use it to every textfield that calls the function without having to write it e.g. 3 times if I want to use it in 3 different date textfields?
Thanks for the replay to Dominik. Make my mind spin
I didn't use event listener but querySelectorAll
Here is the correct version. It works fine
function myFunction() {
var x = document.querySelectorAll(".mydate");
var i;
for (i = 0; i < x.length; i++) {
var dateValue = x[i].value;
if(dateValue == null) {
var grDate = null;
}
else {
var n = dateValue.search("/");
if( n >= 0) {
var res = dateValue.split("/");
var day = res[0];
if( day.length == 1 ) {
day = "0"+day;
}
var month = res[1];
if( month.length == 1 ) {
month = "0"+month;
}
var year = res[2];
var grDate = day+"-"+month+"-"+year;
/*alert(grDate);*/
}
else {
var grDate = dateValue;
}
}
x[i].value = grDate;
}
}
for inputs
<p><input type="text" name="field1" class="mydate" onblur="myFunction()" /></p>
<p><input type="text" name="field2" class="mydate" onblur="myFunction()" /></p>
<p><input type="text" name="field3" class="mydate" onblur="myFunction()" /></p>
Excellent question - because this is the perfect example where a custom element solves the problem.
It's really easy:
customElements.define('my-date', class extends HTMLInputElement {
constructor() {
super();
this.dateConvert = this.dateConvert.bind(this);
this.addEventListener('blur', this.dateConvert);
}
dateConvert() {
if (this.value) {
let n, res, day, month, year;
n = this.value.search("/");
if (n >= 0) {
res = this.value.split("/");
day = res[0];
if (day.length == 1) {
day = "0" + day;
}
month = res[1];
if (month.length == 1) {
month = "0" + month;
}
year = res[2];
this.value = `${day}-${month}-${year}`;
}
}
}
}, { extends: 'input' });
<input is="my-date" />
Now you can even add new date inputs dynamically and they come with your behaviour automatically. No fuddling around in the DOM, just an element that does exactly what you need any time it's in the HTML anywhere.
Please note that unfortunately Safari does not support customizing built-in elements, so you either will have to resort to a polyfill (check https://github.com/webcomponents/polyfills/tree/master/packages/custom-elements or https://github.com/ungap/custom-elements#readme) for that, or use an autonomous custom elements like this:
customElements.define('my-date', class extends HTMLElement {
constructor() {
super();
this.input = document.createElement('input');
this.appendChild(this.input);
this.dateConvert = this.dateConvert.bind(this);
this.input.addEventListener('blur', this.dateConvert);
}
dateConvert() {
if (this.value) {
let n, res, day, month, year;
n = this.value.search("/");
if (n >= 0) {
res = this.value.split("/");
day = res[0];
if (day.length == 1) {
day = "0" + day;
}
month = res[1];
if (month.length == 1) {
month = "0" + month;
}
year = res[2];
this.value = `${day}-${month}-${year}`;
}
}
}
get value() {
return this.input.value;
}
set value(val) {
this.input.value = val;
}
});
<my-date></my-date>
Just as a sidenote, you might want to consider using the built-in API for dateTime conversion/formatting:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
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.
I currently have this filter on my table
(function(document) {
'use strict';
var LightTableFilter = (function(Arr) {
var _input;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('light-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
LightTableFilter.init();
}
});
})(document);
I'm wondering how i can use two date fields with this to act as a date range? i have just tried adding two date fields in but that just gives me the response of two exact dates, not the range in between
Heres my html code for the dates
<label for="Date">Date From:</label>
<input type="date" id="datefrom" class="light-table-filter form-control" style="width:50%" data-table="order-table" placeholder="Filter">
<label for="Date">Date to:</label>
<input type="date" id="dateto" class="light-table-filter form-control" style="width:50%" data-table="order-table" placeholder="Filter">
I think this will need some expanding of you filter function, but you can compare dates with compare operators like >= and <=.
So you need to create dates of your 2 input fields and a date of the table row value. You need to identify the cell if it is indeed the date cell, otherwise it will create date objects of arbitrary cell values. I don't know your full HTML, but this can be done by adding a class, for example (see my code).
For example:
function _filter(row) {
var dateFrom = new Date(document.getElementById('datefrom').value);
var dateTo = new Date(document.getElementById('dateto').value);
dateFrom.setHours(0);
dateTo.setHours(0);
var text = row.textContent.toLowerCase(),
val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
if (!isNaN(dateFrom.getTime()) && !isNaN(dateTo.getTime())) {
var cell = row.querySelectorAll(".date")[0];
var arr = cell.innerText.split('-');
var rowDate = new Date(arr[0],parseInt(arr[1])-1,arr[2]);
if (!isNaN(rowDate.getTime())) {
if (rowDate >= dateFrom && rowDate <= dateTo) {
row.style.display = 'table-row';
} else {
row.style.display = 'none';
}
}
}
}
Make sure the Date constructor receives valid parsable date formats. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date for more info.
EDIT
Updated answer and corrected time.
My database contains the dates. I have a calendar that appears on the User Interface. I want the calendar to reflect the dates from mysql database ie. populate the calendar with the dates from database.
<SCRIPT LANGUAGE="JavaScript">
// day of week of month's first day
function getFirstDay(theYear, theMonth){
var firstDate = new Date(theYear,theMonth,1)
return firstDate.getDay()
}
// number of days in the month
function getMonthLen(theYear, theMonth) {
var oneDay = 1000 * 60 * 60 * 24
var thisMonth = new Date(theYear, theMonth, 1)
var nextMonth = new Date(theYear, theMonth + 1, 1)
var len = Math.ceil((nextMonth.getTime() -
thisMonth.getTime())/oneDay)
return len
}
// create array of English month names
var theMonths = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
// return IE4+ or W3C DOM reference for an ID
function getObject(obj) {
var theObj
if (document.all) {
if (typeof obj == "string") {
return document.all(obj)
} else {
return obj.style
}
}
if (document.getElementById) {
if (typeof obj == "string") {
return document.getElementById(obj)
} else {
return obj.style
}
}
return null
}
// clear and re-populate table based on form's selections
function populateTable(form) {
var theMonth = form.chooseMonth.selectedIndex
var theYear = parseInt(form.chooseYear.options[form.chooseYear.selectedIndex].text)
// initialize date-dependent variables
var firstDay = getFirstDay(theYear, theMonth)
var howMany = getMonthLen(theYear, theMonth)
// fill in month/year in table header
getObject("tableHeader").innerHTML = theMonths[theMonth] +
" " + theYear
// initialize vars for table creation
var dayCounter = 1
var TBody = getObject("tableBody")
// clear any existing rows
while (TBody.rows.length > 0) {
TBody.deleteRow(0)
}
var newR, newC
var done=false
while (!done) {
// create new row at end
newR = TBody.insertRow(TBody.rows.length)
for (var i = 0; i < 7; i++) {
// create new cell at end of row
newC = newR.insertCell(newR.cells.length)
if (TBody.rows.length == 1 && i < firstDay) {
// no content for boxes before first day
newC.innerHTML = ""
continue
}
if (dayCounter == howMany) {
// no more rows after this one
done = true
}
// plug in date (or empty for boxes after last day)
newC.innerHTML = (dayCounter <= howMany) ?
dayCounter++ : ""
}
}
}
// create dynamic list of year choices
function fillYears() {
var today = new Date()
var thisYear = today.getFullYear()
var yearChooser = document.dateChooser.chooseYear
for (i = thisYear; i < thisYear + 5; i++) {
yearChooser.options[yearChooser.options.length] = new Option(i, i)
}
setCurrMonth(today)
}
// set month choice to current month
function setCurrMonth(today) {
document.dateChooser.chooseMonth.selectedIndex = today.getMonth()
}
</SCRIPT>
</HEAD>
<BODY onLoad="fillYears(); populateTable(document.dateChooser)">
<H1>Month at a Glance (Dynamic HTML)</H1>
<HR>
<TABLE ID="calendarTable" BORDER=1 ALIGN="center">
<TR>
<TH ID="tableHeader" COLSPAN=7></TH>
</TR>
<TR><TH>Sun</TH><TH>Mon</TH><TH>Tue</TH><TH>Wed</TH>
<TH>Thu</TH><TH>Fri</TH><TH>Sat</TH></TR>
<TBODY ID="tableBody"></TBODY>
<TR>
<TD COLSPAN=7>
<P>
<FORM NAME="dateChooser">
<SELECT NAME="chooseMonth"
onChange="populateTable(this.form)">
<OPTION SELECTED>January<OPTION>February
<OPTION>March<OPTION>April<OPTION>May
<OPTION>June<OPTION>July<OPTION>August
<OPTION>September<OPTION>October
<OPTION>November<OPTION>December
</SELECT>
<SELECT NAME="chooseYear" onChange="populateTable(this.form)">
</SELECT>
</FORM>
</P></TD>
</TR>
</TABLE>
</BODY>
</HTML>
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