Automatic input sum with jQuery - javascript

I'm making a calculation of more fields and I would like to get the #price + # price2 automatic sum without any jQuery event.
I've been looking for a variety of tutorials but I just managed to get the sum with the click.
I would like her without the click, how can she do it?
function calcscore() {
score = 0;
$(".calc:checked,#TextBox4").each(function() {
score += Number($(this).val());
});
$("#sum").val(score)
$("#price").text(score.toFixed(2));
}
function add() {
var sum = 0;
$(".test").each(function() {
sum += +this.value;
});
return sum; // an add function shouldn't really "alert"
}
$(document).on("change", ".test", function() {
var sum = 0;
$(".test").each(function() {
sum += +$(this).val();
});
$("#price3").val(sum);
});
$(document).ready(function() {
$(".calc").change(function() {
calcscore();
});
$('#add').click(function() {
$("#price3").text(add().toFixed(2));
});
$("#TextBox1").datepicker({
minDate: 0,
maxDate: '+1Y+6M',
altField: "#arrivo",
altFormat: "DD, d MM, yy",
onSelect: function(dateStr) {
var min = $(this).datepicker('getDate'); // Get selected date
$("#TextBox2").datepicker('option', 'minDate', min || '0'); // Set other min, default to today
}
});
$("#TextBox2").datepicker({
minDate: '0',
maxDate: '+1Y+6M',
altField: "#partenza",
altFormat: "DD, d MM, yy",
onSelect: function(dateStr) {
var max = $(this).datepicker('getDate'); // Get selected date
$('#datepicker').datepicker('option', 'maxDate', max || '+1Y+6M'); // Set other max, default to + 18 months
var start = $("#TextBox1").datepicker("getDate");
var end = $("#TextBox2").datepicker("getDate");
var timeDiff = Math.abs((end - start));
var days = Math.ceil(timeDiff / (1000 * 3600 * 24));
$("#TextBox3").val(days);
if (days == 1) {
parseInt($("#TextBox4").val('10'), 10);
parseInt($("#price2").text('10'), 10);
} else if (days == 0) {
parseInt($("#TextBox4").val('10'), 10);
parseInt($("#price2").text('10'), 10);
$("#TextBox3").val('1');
} else if (days == 2) {
parseInt($("#TextBox4").val('12'), 10);
parseInt($("#price2").text('12'), 10);
} else if (days == 3) {
parseInt($("#TextBox4").val('14'), 10);
parseInt($("#price2").text('14'), 10);
} else if (days == 4) {
parseInt($("#TextBox4").val('16'), 10);
parseInt($("#price2").text('16'), 10);
} else if (days >= 5) {
var y = (days) * 4;
parseInt($("#TextBox4").val(y), 10);
parseInt($("#price2").text(y), 10);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form>
<div id="tipo-veicolo">
<input class="calc" type="radio" name="type" value="5"> Macchina
<input class="calc" type="radio" name="type" value="2"> Scooter
<input class="calc" type="radio" name="type" value="10"> Camion
</div>
<div class="variant">
<label>Cambio olio</label>
<input class="calc" type="checkbox" name="check1" id="check1" value="10" />
<label>Cambio gomme</label>
<input class="calc" type="checkbox" name="check1" id="check2" value="2" />
<label>Car valet</label>
<input class="calc" type="checkbox" name="check1" id="check3" value="12" />
</div>
<div id="selezione-data">
<div class="check-in">
<label>Check-In</label>
<input type="text" id="TextBox1" />
</div>
<div class="check-out">
<label>Check-Out</label>
<input type="text" id="TextBox2" />
</div>
<div class="numero-giorni">
<label>Numero Giorni</label>
<input type="text" id="TextBox3" value="0" />
<label>Arrivo</label>
<input type="text" id="arrivo" size="30">
<label>Partenza</label>
<input type="text" id="partenza" size="30">
</div>
</div>
<div class="totale">
<input class="test num1" name="totale" id="TextBox4" value="0" />
<input class="test num2" type="text" name="sum" id="sum" value="0"> Sum: <input type="text" class="sum" readonly="readonly">
</div>
</form>
<p>Total: PHP <span id="price">0</span></p>
<p>Total: PHP <span id="price2">0</span></p>
<p>Total: PHP <span id="price3">0</span></p>
<input id="add" type="button" value="add" />
Thank you and good day

Im not sure if I understand you correctly, but you can't do it without using any events.
You can achive automatic aggregation by using, for example, input event in jQuery.
Here is example of this:
$('.num1, .num2').on('input', function () {
$('.sum').val(parseInt($('.num1').val()) + parseInt($('.num2').val()));
});
Here is jfiddle.

Try this to achieve your goal, place it the end of document.ready event
$(document).ready(function() {
..
..
..
$("input").change(function() { // place it at the bottom of other events, this will listen for all inputs
$("#price3").text(add().toFixed(2)); // after input changes it will calculate
});
});
demo
Hope helps,

Related

how to implement multiple countdowns on the same DOM element

I have a DOM element, that contains values (milliseconds) from my database, and I want to implement a countdown for the values. For example, I can have 4 product deals in a section, with different duration in milliseconds, and i want to dynamically create different countdowns(HH:mm:ss) for each deal according to its duration.
Currently, the duration values (milliseconds) are stored in a hidden input field for each deal in the section.
<input type="hidden" name="" id='duration' value="{{this.deals.duration}}">
What i tried (it works fine for only one product deal). I used moment.js for the duration. and also for the countdown here:
<script type="text/javascript">
$(document).ready(function(){
console.log($('#duration').val());
var interval = 1000;
var durations = $('#duration').val();
setInterval(function(){
durations = moment.duration(durations - interval, 'milliseconds');
// console.log(durations);
$('#countdown').text(durations.hours() + ":" + durations.minutes() + ":" + durations.seconds())
}, interval);
})
</script>
Thanks very much :)
To add another answer to this question...
No dependencies (jQuery,Moment.js) and only for 24 hour duration (days,months,years are not calculated).
function countDown(elClass) {
let labels = document.querySelectorAll(elClass);
let now = Date.now();
labels.forEach((label,key) => {
let duration = document.getElementById(label.getAttribute('for')).value;
if(duration <= 86400000) {
let futureDate = now + parseInt(duration);
let counterInterval = setInterval(() => {
let diff = futureDate - Date.now();
if(diff <= 0) {
clearInterval(counterInterval);
return;
}
if(diff > 0) {
let milliseconds = diff%1000;
let seconds = parseInt(diff/1000)%60;
let minutes = parseInt(diff/(60*1000))%60;
let hours = parseInt(diff/(60*60*1000))%24;
label.innerHTML = hours.toString().padStart(2, '0')+':'+minutes.toString().padStart(2, '0')+':'+seconds.toString().padStart(2, '0')+'<br>';
}
},1000);
}
});
}
countDown('.countdown');
<input type="hidden" name="a" id="a" class='duration' value="5000"><label for="a" class="countdown"></label>
<input type="hidden" name="b" id="b" class='duration' value="15000"><label for="b" class="countdown"></label>
<input type="hidden" name="c" id="c" class='duration' value="190000"><label for="c" class="countdown"></label>
<input type="hidden" name="d" id="d" class='duration' value="2003200"><label for="d" class="countdown"></label>
<input type="hidden" name="e" id="e" class='duration' value="20067100"><label for="e" class="countdown"></label>
<input type="hidden" name="f" id="f" class='duration' value="86023104"><label for="f" class="countdown"></label>
$(document).ready(function(){
var interval = 1000;
setInterval(function(){
$('.duration').each(function () {
var t = Number($(this).val()) - interval;
if (t>=0) {
var d = moment.duration(t, 'milliseconds');
$(this).next('.countdown').text([
String(d.hours()).padStart(2,'0'),
String(d.minutes()).padStart(2,'0'),
String(d.seconds()).padStart(2,'0')
].join(':'));
$(this).val(t);
}
});
}, interval);
})
input + span {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<input type="hidden" name="a" class='duration' value="5000"><span class="countdown"></span>
<input type="hidden" name="b" class='duration' value="15000"><span class="countdown"></span>
<input type="hidden" name="c" class='duration' value="20000"><span class="countdown"></span>

Auto-populate total day in textbox if choose from two dates

I want to display total day in text box automatically if I choose from two dates, but I can not get it. If I don't use Javascript, it works. Datepicker can't work if haven't used Javascript. How can I do that?
This is my script:
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" "/>
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" disabled="disabled" "/>
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
This is java script:
<!--calendar Java script -->
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- Datepicker -->
<script type="text/javascript">
$(document).ready(function () {
$('#example2').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- calculate leave total day -->
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
</script>
There are quite a few bits in your code that need changing / fixing, so here is a working example based on your original code.
<input class="form-control" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" />
<input class="form-control" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" />
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
$(document).ready(function(){
$('#example1').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
$('#example2').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
});
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
Working Demo
changeDate event is triggered every time the date is selected or changed
DatePicker(Events)
HTML
<input placeholder="Start Date " type="text" id="StartDate" />
<input placeholder="End Date " type="text" id="EndDate" />
<input type="text" id="datediff" />
JS
$('#StartDate,#EndDate').datepicker({
format: "yyyy-mm-dd",
autoclose: true,
});
$('#StartDate,#EndDate').datepicker().on('changeDate', function () {
if ($('#StartDate').val() != '' && $('#EndDate').val() != '') {
var date1 = new Date($('#StartDate').val());
var date2 = new Date($('#EndDate').val());
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#datediff').val(diffDays);
}
})

Form with radio buttons and one input field. Calculate the value depending on radio button selcted

I would like to convert the temperature given in Celsius to Fahrenheit degrees or the other way round. I would like the unit to be chosen via radio button form and the converted units calculated with JS function. However, I am doing something wrong, and I am not sure what exactly. Any help would be appreciated. Thanks.
<body>
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p id="myForm>
<form name="units" onsubmit="return convertTemp();" method="post">
<input type="number" id="temp"><br>
Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
And here is my JavaScript function:
function convertTemp() {
alert("Włączyła się");
var x = document.Jednostki.Temperature.value;
if (x == "c"){
alert("Celsjusz");
}
else if (x == "f"){
alert("Fahrenheit");
}
returns false;
}
Here is what I would suggest
window.addEventListener("load", function() {
document.getElementById("units").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Włączyła się");
var num = parseInt(document.getElementById("temp").value, 10);
if (document.getElementById("c").checked) {
console.log("Celsjusz");
document.getElementById("wynik").innerHTML = num + "C," + (Math.round(num * 9 / 5) + 32) + "F";
} else if (document.getElementById("f").checked) {
console.log("Fahrenheit");
document.getElementById("wynik").innerHTML = num + "F," + (Math.round((num - 32) * 5 / 9)) + "C";
}
});
});
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p>
<form id="units">
<input type="number" id="temp"><br> Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
Using querySelector:
window.addEventListener("load", function() {
document.getElementById("units").addEventListener("submit", function(e) {
e.preventDefault();
console.log("Włączyła się");
const num = parseInt(document.getElementById("temp").value, 10);
const type = document.querySelector("[name=Temperature]:checked").value;
if (type==="c") {
console.log("Celsjusz");
document.getElementById("wynik").innerHTML = num + "C," + (Math.round(num * 9 / 5) + 32) + "F";
} else {
console.log("Fahrenheit");
document.getElementById("wynik").innerHTML = num + "F," + (Math.round((num - 32) * 5 / 9)) + "C";
}
});
});
<p>Convert temperatures to and from celsius, fahrenheit.</p>
<p>
<form id="units">
<input type="number" id="temp"><br> Temperature in:
<fieldset>
<input type="radio" name="Temperature" id="c" value="c" checked><label for="c">Celsius degrees</label>
<input type="radio" name="Temperature" id="f" value="f"><label for="f">Fahrenheit degrees</label>
</fieldset>
<input type="submit" value="Oblicz">
<form>
</p>
<p id="wynik"></p>
First issue I see: returns false; should be return false; (no s).
You should also retrieve the values using document.getElementById():
function convertTemp() {
alert("Włączyła się");
var celsius = document.getElementById('c');
var fahr = document.getElementById('f');
if (c.checked){
alert("Celsjusz");
}
else{
alert("Fahrenheit");
}
return false;
}
document.getElementById("units").onsubmit = convertTemp;
using jquery you can do it raplce this line
var x = document.Jednostki.Temperature.value;
to
var x = $('input[name="Temperature"]:checked').val()
you can see it working here
to get jquery click here

Change value of input box based on selected item and other value

So basically, I am creating an application form for gym membership.
The base cost is $100. If juggling is selected, the cost will increase by $50.
Also, the base cost will increase by $50 if the 'BMI' is > 25 and <= 30. If the 'BMI' is > 30, it will increase by $100 instead.
This is my code. It is not working as intended. Would like some help. Thanks a lot.
<!DOCTYPE html>
<html>
<head>
<title>UWS application form</title>
<link rel="stylesheet" href="Prac1Task2.css" />
</head>
<body>
<form>
<fieldset>
<legend>Fitness Details</legend>
Favourite Activities: <br/>
<input type="checkbox" name="activity" value="cycling" id="cycling"><label for="cycling">Cycling</label>
<input type="checkbox" name="activity" value="50" id="juggling" onchange="update(this);"><label for="juggling">Juggling</label>
<br/>
<br/>
<label for="height">What is your height (Meters)</label><br/>
<input type="number" name="height" id="height" class="input" onchange="getBMI()">
<br/>
<label for="weight">What is your weight? (kg)</label><br/>
<input type="number" name="weight" id="weight" class="input" onchange="getBMI()">
<br/>
<label for="bmi">BMI:</label><br/>
<input type="number" name="bmi" id="bmi" class="input" value="" readonly>
<script>
function getBMI()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
document.getElementById("bmi").value = (weight / height) / height;
var bmi = document.getElementById("bmi");
var price = document.getElementById("price").value;
if (bmi.value > 25 && bmi.value <= 30)
{
parseInt(price.value) += parseInt(50);
document.getElementById('price').value = price.value;
}
else if (bmi.value > 30)
{
document.getElementById("price").value = document.getElementById("price").value + 100;
}
}
</script>
</fieldset>
<br/>
<fieldset>
<legend>Application Details</legend>
Date of Application:<br/>
<input class="input" id="date" name="date" readonly />
<script>
var timetime = new Date();
document.getElementById("date").value = (timetime.getDate() + "/" + (timetime.getMonth() + 1)
+ "/" + timetime.getFullYear());
</script>
<br/><br/>
Cost of Application: <br/>
$<input type="number" class="input" id="price" name="price" step="0.01" value="100" readonly />
<script>
var total = 100;
function update(feature) {
if(feature.checked == true){
total += parseInt(feature.value);
document.getElementById('price').value = total;
}
if(feature.checked == false){
total -= parseInt(feature.value);
document.getElementById('price').value = total;
}
}
</script>
</fieldset>
<br/>
<input type="submit" value="Submit" class="button">
</form>
</body>
</html>
You haven't mentioned the exact issue which you are facing. However, I think there should be some problem with this line of code.
parseInt(price.value) += parseInt(50);
parseInt() is a function and you cannot assign values to it.
It should be some thing like this
price.value = parseInt(price.value) + parseInt(50);
Also price.value is not a proper reference because you are assigning document.getElementById("price").value; to it. So you should be using price instead of price.value

How to use multiple button for same function in javascript?

I am new in javascript. I want to create multiple button with same function and result will be shown in same place. From my code I want to change tip1 value for every button click event. How can I do this? Please help me if any one have any idea.
My codes are below:
<form id="calculator">
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button onclick="calculate()" id="1">Button1</button>
<button onclick="calculate1()" id="2">Button2</button>
</form>
<script type="text/javascript">
function calculate () {
var amount = $('#amount').val();
var year = $('#year').val();
if (button 1) {
var tip1 = (1 + 115 / 100);
}
else if (button 2) {
var tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
return false;
}
$('#calculator').submit( calculate );
</script>
You can do it like this:
function calculateF(target) {
var amount = parseFloat($('#amount').val());
var year = parseFloat($('#year').val());
if (target == 1) {
var tip1 = (1 + 115 / 100);
} else if (target == 2) {
var tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val(tip.toFixed(2));
$('#total').val(total.toFixed(2));
return false;
}
$('button').click(function(e) {
calculateF($(e.target).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button id="1">Button1</button>
<button id="2">Button2</button>
Also, by passing ID directly
function calculate (id) {
var amount = $('#amount').val();
var year = $('#year').val();
var tip1 = 0;
if (id == "1") {
tip1 = (1 + 115 / 100);
}
else if (id == "2") {
tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button onclick="calculate(this.id)" id="1">Button1</button>
<button onclick="calculate(this.id)" id="2">Button2</button>
You are declaring var tip1 at wrong places.
Just Use this to call the function calculate(id).
$('button').click(function(e) {
calculate(this.id);
});
HTML
<form id="calculator">
<p>Amount: <input id="amount" /></p>
<p>Years: <input id="year" /></p>
<hr />
<p>Tip: <input id="tip" disabled="disabled" /></p>
<p>Total: <input id="total" disabled="disabled" /></p>
<button id="1">Button1</button>
<button id="2">Button2</button>
</form>
calculate() function
function calculate () {
var amount = $('#amount').val();
var year = $('#year').val();
var tip1;
if (id=="1") {
tip1 = (1 + 115 / 100);
}
else if (id=="2") {
tip1 = (1 + 215 / 100);
}
var tip = Math.pow(tip1, year);
var total = amount * tip;
$('#tip').val( tip.toFixed(2) );
$('#total').val( total.toFixed(2) );
return false;
}

Categories