I am working on a project where I have to add a database value to in input value.
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
</div>
In above code 680 will come from the database. Here I want to add an input number to that 680. I am very new to jQuery.
My JavaScript code is
$(document).ready(function() {
var total = 0;
$("input").keyup(function(){
var priceList = $('.price');
$.each(priceList, function(i, price){
total += parseFloat($(price).text());
});
alert(total);
});
});
</script>
In this it outputs "NaN".
In this it outputs "NaN".
You get this message since you're trying to loop through div's and parsing the text of them, when it's empty. You need to loop over input's instead.
You could init the total with the database value then loop through the input's and add the parsed values to total in every iteration.
NOTE: Use input event instead when you track the user input since it's more efficient.
Multiple inputs:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
$('.price input').each(function() {
total += parseFloat($(this).val()) || 0;
});
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Single input:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
total += parseFloat($(this).val()) || 0;
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Here you go
var result = 0;
var price = +$('#price').text();
$('input[type="number"]').on('input', function() {
var val = +$(this).val();
result = parseInt(val + price);
$('#price').text(result)
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price" id="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
Related
I'm really new to JS. I am working on the if else statement and returning the total using the button. I also want to return some other input from HTML file also using the same button or on the same function as my calculate function. How do I return the total amount, name(input), number(input), from html to that one button as well?
If you don't get my question please run the code and see that it is not printing out the other input value. Thank you for helping me out.
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
You are very close just need a few tweaks.
You shouldn't repeat ids, so in that case, to make it easier to understand, we can rename the input with id name to name_input, so you can retrieve its value as
document.getElementById('name_input').value
You can add that to your function and assign it to the innerHTML of name inside the function calculate() and so on with as many actions as you want
Working snippet:
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
document.getElementById("name").innerHTML = document.getElementById("name_input").value;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name_input" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
I am making a mortgage calculator and am trying to clear all the inputs when the clear button is presses. I can't seem to get it to work. Below is my html and JavaScript code, I have also tried setting the inputs = null and that didn't work.
HTML:
<div class="calculator">
<h1>Mortgage Calculator</h1>
<div class="input-container">
<label for="Loan-amount">Total Loan Amount</label>
<input type="number" name="Loan-amount" id="total" min="0">
</div>
<div class="input-container">
<label for="down-payment">Down payment</label>
<input type="number" name="Loan-amount" id="down" min="0">
</div>
<div class="input-container">
<label for="interest-rate">Interest rate %</label>
<input type="number" name="interest-rate" id="interest" min="0">
</div>
<div class="input-container">
<label for="loan-term">Loan Term (in years)</label>
<input type="number" name="loan-term" id="duration" min="0">
</div>
<div class="answer">
<h2>Estimated payment:</h2>
<p id="paragraph-value"></p>
</div>
<div class="button-container">
<button id="submitBtn">Calculate</button>
<button id="clearBtn">Clear</button>
</div>
<p id="alert"></p>
</div>
JavaScript:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
let total = document.getElementById("total").value;
let interest = document.querySelector("#interest").value;
let duration = document.querySelector("#duration").value;
let downPayment = document.querySelector("#down").value;
total = "";
interest = "";
duration = "";
downPayment = "";
});
You're not setting a value to the inputs, you're just over-writing the value of a varable:
total = "";
To set the value of the input, you'd set the .value property on the input:
document.getElementById("total").value = "";
For example:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
document.getElementById("total").value = "";
});
<input type="number" id="total" />
<button id="clearBtn">Reset</button>
At a more generic level, you seem to be confused about the difference between these two things:
var total = document.getElementById("total").value;
total = "";
and:
var total = document.getElementById("total");
total.value = "";
In the first case the variable holds a copy of the value itself, and you're re-assigning the variable to a new value. This does nothing to the element.
But in the second case the variable holds a reference to the element, and you're updating a property on that element.
I have a multiple input rows and all rows have a total column at the end. Now, I want to put the total result of each rows in column Total. I tried but it returns NaN value instead of total result. Attached is my view & script please help what I am missing??? Thanks
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('.dosiaPlace').find('input').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('.dosiaPlace').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dosiaPlace">
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
</div>
Result:
The container, the .dosiaPlace, I presume, has 3 inputs: the .bgpending, the .registered, and the .total-row. Your el.closest('.dosiaPlace').find('input') finds all 3 of those, including the .total-row. But the .total-row is empty (initially), so
totalRow = totalRow + parseInt($(this).val());
for it results in
totalRow = totalRow + parseInt('');
And the empty string can't be parseInt'd (results in NaN). (You also probably don't want to be including the .total-row anyway)
Use input:not(.total-row') instead of input:
$('body').on('change', '.bgpending, .registered', function() {
var el = $(this);
var totalRow = 0;
el.closest('body').find('input:not(.total-row)').each(function() {
totalRow = totalRow + parseInt($(this).val());
});
el.closest('body').find('.total-row').val(totalRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
<label>#lang('dashboard.pastyear'):</label>
<input type="number" value="0" class="form-control bgpending" name="bgpending[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.warida'):</label>
<input type="number" value="0" class="form-control registered" name="registered[]" />
</div>
<div class="col-md-2">
<label>#lang('dashboard.total'):</label>
<input type="text" class="form-control total-row" />
</div>
Your variable get null value or NaN just asign o if it is nan or empty
if(totalRow=='' || totalRow ==NaN )
{
totalRow=0;
}
I have an HTML form with three textboxes. I want to sum them automatically using jQuery. At the same time, I want to use if–else statements to check if the result in third textbox is greater than 100. The value in the next (forth textbox)should be A.
See the code below :
<form>
<input type="text" class="number">
<input type="text" class="number">
<br>
<input type="text" id="total" disabled />
<input type="text" id="total2" disable />
<!--i want the letter A to appear in forth textbox if the value in third textbox is > 100 ---->
</form>
<script>
$('.number').keyup(function() {
var sum = 0;
$('.number').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
if ($('#total').val(sum) > 100) {
form.total2.value = "A";
}
});
}
});
</script>
</body>
</html>
$('.number').on('keyup',function(){
var sum = 0;
var grade = 'B';
$('.number').each(function(){
sum += parseInt($(this).val());
});
$('#sum').text(sum);
if(sum>100){
grade = 'A';
}
$('#grade').text(grade);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" class="number" placeholder="number 1">
<input type="textbox" class="number" placeholder="number 2">
<div>
Your total mark is <span id="sum">0</span>.
<br>
Your grade is <span id="grade">F</span>.
</div>
You can use the following solution:
$('.number').keyup(function() {
var sum = 0;
$('.number').each(function() {
sum += parseInt($(this).val());
});
$('#total').val(sum);
if (sum > 100) {
$('#total2').val("A");}
});
Given that I have 5 input fields that are linked to their own price, I want to be able to grab the value of the input multiplied by its specific price and return that value to the dom.
This is what's being rendered, there are 5 with a unique price.
I'm not sure how to link each input to its specific price, add the prices of all 5 inputs (if there are any) and post them on the dom.
I'm trying to get the data-price of the .class p tag, loop through them, link it to their input add the sum and post the sum to the dom
<section data-itemid="${menuObj.id}">
<div class="amount">
<input type="number" placeholder="Quantity" min="0" name="${menuObj.id}">
</div>
<div class="item">
<h1>${menuObj.name}</h1>
<p class="food">${menuObj.description}</p>
<p class="price" data-price="${menuObj.price}">${menuObj.price}</p>
</div>
</section>
I have it working for one, but not sure how to get them working for all
$(function() {
$('input').on('keyup', function() {
var input = $('.amount input').val();
var price = $('.price').data('price');
var final = $('.finalprice p');
var total = input * price;
final.text(total);
});
})
For dynamic content use event delegation to bind events.
$(document).on('input', '.menu-class div[class="amount"] input[type="number"]', function() {...}
Use input event to cover every change on your input Quantity.
Apply a class to the section. i.e: .menu-class
Approach
Basically, loop over the section and collect the amount.
var total = 0;
$('.menu-class').each(function() {
var $section = $(this);
var input = $section.find('div.amount [type="number"]').val();
var price = $section.find('.price').data('price');
total += (input * price);
});
$finalPrice.text(total);
Snippet
$(function() {
var $finalPrice = $('.finalprice p');
$finalPrice.on('calculate', function() {
var total = 0;
$('.menu-class').each(function() {
var $section = $(this);
var input = $section.find('div.amount [type="number"]').val();
var price = $section.find('.price').data('price');
total += (input * price);
});
$finalPrice.text(total);
});
$(document).on('input', '.menu-class div[class="amount"] input[type="number"]', function() {
$finalPrice.trigger('calculate');
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class='col-md-6 col-xs-6'>
<section class='menu-class' data-itemid="111">
<div class="amount">
<input type="number" placeholder="Quantity" min="0" name="quant_111">
</div>
<div class="item">
<h1>My Meat :-)</h1>
<p class="food">Meat</p>
<p class="price" data-price="1000.0">1,000.00</p>
</div>
</section>
<hr>
<section class='menu-class' data-itemid="112">
<div class="amount">
<input type="number" placeholder="Quantity" min="0" name="quant_112">
</div>
<div class="item">
<h1>My bread :-)</h1>
<p class="food">Bread</p>
<p class="price" data-price="2000.0">2,000.00</p>
</div>
</section>
</section>
<section class='col-md-6 col-xs-6'>
<section class='finalprice'>
<h1>Final price</h1>
<p>
</p>
</section>
</section>
$('.amount input') returns an array-like object of all dom elements that match the selector. I believe $('.amount input').val(); will return value from the first item in the array
You may want to localize finding inputs, like below:
$(function() {
$('input').on('keyup', function() {
var $section = $(this).closest('section');
var input = $section.find('.amount input').val();
var price = $section.find('.price').data('price');
var final = $section.find('.finalprice p');
var total = input * price;
final.text(total);
});
});