Alarm in javascript/Jquery to update database - javascript

I'm trying to create an Alarm where I have to detect when a product starts and when ends.
It is possible to have a general alarm? I mean I won't be always on the same webpage... I mean I'd like to start the alarm on localhost:8080/createProduct, and if I'm in localhost:8080/products if the alarm fires get notified.
What I have to do is an Update to my db.
On my createProduct I have the startDate and endDate, I've found a method on this webpage where I found this method :
function getTimeRemaining(endtime){
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor( (t/1000) % 60 );
var minutes = Math.floor( (t/1000/60) % 60 );
var hours = Math.floor( (t/(1000*60*60)) % 24 );
var days = Math.floor( t/(1000*60*60*24) );
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
So I can know the hours left and I can put it on this function from javascriptKit, instead of going to an URL I will have to update on my db.
Do you guys know any way to update the state of the product to the DB depends if it's ability or not?
I mean able is that startDate is equals than the current date (It will be on a form where you can choose the startDate), and if the endDate is the same than the current date the product would be disabled.
Hope I have explained correctly.
By the way, my form is like this :
<form method="POST" id="formdata" action="/createProduct" enctype="multipart/form-data">
<table>
<tr>
<td><label >Name</label>:</td>
<td><input type="text" name="name" id="name" required="required"/></td>
</tr>
<tr>
<td><label >Start Date</label>:</td>
<td><input type="text" name="startDate" id="startDate" required="required" autocomplete="false"/></td>
<td><input type="text" id="localTime" name="localTime" value="" hidden="hidden"/></td>
</tr>
<tr>
<td><label >EndDate</label>:</td>
<td><input type="text" name="endDate" id="endDate" required="required" autocomplete="false"/></td>
</tr>
</table>
<input type="submit" id="sendButton" value="Create product" />
</form>

Related

auto change birth date if given birth date given?

I have 2 input one is input for "Birth Date" and the one is for the Age, is there anyway, if I change the Birth Date, the Age input automatically change.
<input type="text" name="birthdate" value="07/24/1988" />
<input type="text" name="age" value="32" />
You can calculate the difference of current date and the date entered in years and then change the value of the age on keyup event like below
function age(dt) {
var diff = ((new Date().getTime() - new Date(dt).getTime()) / 1000) / (60 * 60 * 24);
document.getElementById("age").value = Math.abs(Math.round(diff / 365.25));
}
<input type="text" name="birthdate" value="07/24/1988" onkeyup="age(this.value)" />
<input type="text" name="age" value="32" id="age" />

Get NaN as result in my age field after I select the date in datepicker

I am trying to calculate the age field but I keep getting NaN as the answer.
I had try to correct my code but I am still unable to detect the error. Can someone help me to point out the error? Appreciate the help very much.
function getAge() {
var dob = document.getElementById('DOB').value;
dob = new Date(dob);
var today = new Date();
var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
document.getElementById('Age').value = age;
}
<div class='input-group date' id='DOB' style="width:195px">
<input type='text' class="form-control" name="DOB" id="DOB" placeholder="mm/dd/yyyy" onblur="getAge()" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<input type="text" class="form-control" style="width:64px" id="Age" name="Age" value="" placeholder="eg. 21" maxlength="2" />
You have assigned the id DOB to the outer div as well as input field.
Change the id of outer div to something else and it should work.
You have two elements with the same id="DOB". document.getElementById('DOB') will return the div. As such, dob is undefined, and the calculation gives NaN.

extract year from date and calculate datedifference

I am relative new in coding and recently i have to do some date manipulations with data entered in a form. I searched a lot and I haven't found the solution that works for me.
Here is the issue:
The user enters following data in datetime-local fields in HTML:
1) Year of entering College (date 1)
2) Year of graduation (date 2)
3) Birthday (date 3)
I need a JQuery or a JavaScript script that uses this dates and output following:
1) Year of admitting, based on the admittion date (I know there is a getFullYear function, but I couldn't use it right...) >>> result1
2) Age at graduation (date difference between Birthdate and date of Graduation. >>> result2
I tried with adding datepicker but somehow I got really awful looking calendar which was displayed over the boxes. I couldn't install datetimepicker...
Thank you in advance. Your help is appreciated.
Here is my HTML code.
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
You didn't include the js code which is more important for this question. I'll include a couple functions that should help.
To find a year from a date, I use the following function
function getYearFromDate(date){
const yearFromDate = new Date();
yearFromDate.setTime(date.getTime());
yearFromDate.setFullYear(date.getFullYear() + 1);
return yearFromDate;
}
console.log(getYearFromDate(new Date()));
And the graduation age copied mostly from Calculate age given the birth date in the format YYYYMMDD
function getYearsBetween(oldDate, newDate) {
var age = newDate.getFullYear() - oldDate.getFullYear();
var m = newDate.getMonth() - oldDate.getMonth();
if (m < 0 || (m === 0 && newDate.getDate() < oldDate.getDate())) {
age--;
}
return age;
}
Including moment.js is also an option, but it's a large library I like to avoid if I can.
EDIT I thought you wanted year + 1 day. Getting the full year from the date is even easier.
const date = new Date();
console.log(date.getFullYear());
Edit: All together now
function updateGradYear(event) {
console.log(event.target.value);
let date = new Date(event.target.value);
document.querySelector('#result1').value = date.getFullYear();
}
function updateAge() {
let gradDate = new Date(document.querySelector('#date2').value);
console.log(document.querySelector('#date3').value);
let birthdate = new Date(document.querySelector('#date3').value);
document.querySelector('#result2').value = gradDate.getFullYear() - birthdate.getFullYear();
}
// set some default values
let today = new Date();
document.querySelector('#date1').value = today.toISOString().split('.')[0];
document.querySelector('#result1').value = today.getFullYear();
document.querySelector('#date2').value = today.toISOString().split('.')[0];
let birthdate = new Date(today.getTime);
birthdate.setFullYear(1984);
console.log(birthdate.toISOString().slice(0, 10).replace(/\//g, "-"));
document.querySelector('#date3').value = birthdate.toISOString().slice(0, 10).replace(/\//g, "-");
updateAge();
<input id="date1" type="datetime-local" onchange="updateGradYear(event)" />
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="number" readonly="true" name="year" placeholder="=(getFullYear from date1)" />
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" onchange="updateAge()" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" onchange="updateAge()" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)" /></textarea>
<label for="result2">age</label>
<br />
Let me know how this works for you! And as i said please enter all the fields while running this code!
$('#date1, #date2').on('blur',function(){
var dc = document.querySelector('input[id="date1"]');
var date = new Date(dc.value);
var collegeadmission = date.getFullYear();
$('#result1').val(date.getFullYear());
dc = document.querySelector('input[id="date2"]');
date = new Date(dc.value);
var collegegrad = date.getFullYear();
if(! isNaN(collegegrad))
$('#result2').val(collegegrad - collegeadmission);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
check out this url:http://jsbin.com/vebiwogipu/edit?html,js,output
Make sure u fill all the dates and time properly as you discussed in your html.
Similarly you can attach the output on click or change event.
and aso you can leverage getMonth() and getDay() in the code to get desired output.
Take a look at the label and may be alert, when you click the button, it shows year out of your first date field. As i said you need to add the logic for rest.
let me know if it makes sense, if not please add more information to make me understand!

how to add a basic input discount on javascript

This is the code i want to create this form were you input all the information like price, quantity and %discount and have the discount amount shown the subtotal and the total
as the discount amount being the %discount divided by 100 and then multiplied by the subtotal. The subtotal is made by multiplying the price by quantity. And the total is made by multiplying the subtotal by discount as you can see i have the form complete and i have almost all the code on the javascript but it seems i cant make it work with the discount. Please help !
JS:
$('#CAT_Custom_490527').keyup(function () {
var quantity = $("#CAT_Custom_490527").val();
var iPrice = $("#CAT_Custom_490526").val();
var subtotal = quantity * iPrice;
$("#CAT_Custom_491101").val(subtotal);
var x = $("#CAT_Custom_491074").val();
var y = 100
var division = x / y
var multi = division * subtotal
$("CAT_Custom_491074").val(division);
var total = subtotal * multi;
$("#CAT_Custom_490531").val(total);
// sets the total price input to the quantity * price
});
HTML:
<tr>
<td>
<label for="CAT_Custom_490526">Precio <span class="req">*</span>
</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_490526" id="CAT_Custom_490526" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_490527">Cantidad <span class="req">*</span>
</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_490527" id="CAT_Custom_490527" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_491074">%Descuento</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_491074" id="CAT_Custom_491074" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_491218">Descuento</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_491218" id="CAT_Custom_491218" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_491101">Subtotal</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_491101" id="CAT_Custom_491101" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_490531">Total <span class="req">*</span>
</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_490531" id="CAT_Custom_490531" class="cat_textbox" />
</td>
</tr>
Trouble spots I see:
Incorrect Math (thanks to answer by krb686 - please upvote that answer since it is helpful)
Typo in selector - missing # (thanks to answer by Kundan Singh Chouhan - please upvote that answer since it is helpful)
After correcting the typo above, you are now overwriting the discount percent. I bet you meant that to be used for the discount value field: #CAT_Custom_491218. This would be much easier to detect ahead of time if you use meaningful ids instead of auto-generated ids.
You are only evaluating this function when the quantity field is changed. If you change, for example, the discount percent, the subtotal and total are not re-evaluated.
You are only watching keyboard events. If the value was changed using the mouse only (copy/paste or drag/drop), the subtotal and total are not re-evaluated. Also handle oninput (a new event for html5) and onchange.
To bind to all of the inputs and detect more events than just keyup:
$("input").on("input keyup change", function () {
...
Demo with all the above changes applied
You missed the "#" form your textbox ID, it should be
$("#CAT_Custom_491074").val(division);
This will fix your issue.
Your math is incorrect
So if I enter 50 in the discount box, x = 50, y = 100,
division = x/y = 50/100 = 0.5
Say subtotal = $100, then multi = subtotal * division = $100 * 0.5 = $50
Then, total = subtotal * multi = $100 * $50 = $5000
You shouldn't be multiplying subtotal * multi.
Why don't you just do:
total = subtotal * (1 - discount/100)
Essentially (1 - discount/100) is your multiplier. If I enter 12 for discount, it becomes:
total = ($100) * (1 - 12/100), or ($100) * 0.88, or $88
Or
Just change your last line of code to:
total = subtotal - multi
multi isn't holding a multiplier, it's holding the amount you want to take off the total.

Subtract an integer from a calculated total

I've built a script to add quantities/units and generate a total that displays sales tax.
How can I get this calculator to recognise #discount and subtract it from the total before the GST (10% sales tax) is calculated and added?
Also, is it possible to generate the total when the page loads? Instead of a user having to press the 'Generate total' button?
HTML
<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>
<input type="button" value="Generate Total" onclick="total()" /><br><br>
Discount <input type="text" id="discount" name="discount" value="500"/><br><br>
Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />
JS
function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");
for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
continue;
}
total_value += parseFloat(all_others[i].value);
}
document.getElementById("units_total").value = (total_value).toFixed(1);
document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);
document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);
document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
Firstly, to get your function to execute on window load, wrap it in a load event:
window.onload = function() {
total();
}
Secondly, to get it to figure in discount, you just need to modify your variable a few times, but then when adding them together, make sure you parse them with .parseFloat():
if (document.getElementById('discount').value != '') {
var discount = document.getElementById('discount').value;
}
else {
var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);
document.getElementById("sub_total").value = sub_total;
document.getElementById("gst_total").value = gst;
document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);
DEMO
First of all, I suggest you to perform validation and computations both server side and client side. The first ensures security while the second improves the responsiveness of the UI.
Said that, you'd better introduce several support variables and perform computation on them. You should get the value from the elements you are interested into using getElementById and store it in variables.
Then you should perform computation on that variables and finally place the results in the elements you want to use to display them to the user.
To perform the operation when the page loads have a look at this.

Categories

Resources