jquery each() iteraton - javascript

I want to multiply the input value with p tag when press the button. My html structure is like this:
<div class="table">
<input class="input" type="text" />
<p>10</p>
</div>
<div class="table">
<input class="input" type="text" />
<p>20</p>
</div>
<div class="bill"></div> // the result must be displayed in this tag
<button class="button">Calculate</button>
I use each method to select input elements and it is my jquery structure:
$(function() {
function calculate()
{
$('input.input').each(function(index) {
var inputValue = $(this).val();
var valueP = $(this).next('p').text();
var result = inputValue * valueP;
$('.bill').text(result);// displays only last multipled result
console.log(result); // displays all multipled results
});
}
$('.button').click(function() {
calculate();
});
});
I achive to multiply input value with p tag but the problem is that only last multiplied input value displays in the class with "bill". But it looks fine with console.log
Also, it is fine with "document.write(result)". How can I fix this problem?
By the way, someone could say me please how can I sum all multiplied results!
Thanks for advance!

try this demo
function calculate() {
var result = 0;
$('input.input').each(function(index) {
var inputValue = Number($(this).val());
var valueP = Number($(this).next('p').text());
result += inputValue * valueP;
//as you were adding here it will each time update the .bill
console.log(result);
});
$('.bill').text(result);
}
$('.button').click(calculate);​
update
demo for showing all calculated result beside adding them
function calculate()
{
//var result = 0;
$('input.input').each(function(index) {
var inputValue = Number($(this).val());
var valueP = Number($(this).next('p').text());
var result = inputValue * valueP;
$('.bill').append(result+"<br/>");
console.log(result);
});
}
$('.button').click(calculate);​

Please try this:
function calculate() {
var result = 0;
$('input.input').each(function(index) {
var inputValue = Number($(this).val());
var valueP = Number($(this).next('p').text());
result += inputValue * valueP;
$('.bill').append(result);
console.log(result);
});
}
$('.button').click(calculate);​

Related

get the html of the child div if the checkbox in the parent div has been checked in javascript

I have the following HTML:
<div id="chkBox20">
<input type="checkbox" id="box20" name="rooms[]" value="20" class="box"/>
<div class="specialprice2" style="float:left;">68.00</div>
</div>
<div id="chkBox21">
<input type="checkbox" id="box21" name="rooms[]" value="21" class="box"/>
<div class="specialprice2" style="float:left;">68.00</div>
</div>
<div id="chkBox22">
<input type="checkbox" id="box22" name="rooms[]" value="22" class="box"/>
<div class="specialprice2" style="float:left;">155.00</div>
</div>
Some or none of those checkboxes might be checked.
If some of the boxes are checked, I have script that display the sum for checked checkboxes.
What I am trying now is to update the result if the user check or uncheck any of the checkboxes.
Here is the javascript that I have now:
$(document).ready(function(){
var sum = 0;
$('.specialprice').each(function(i, el) {
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
});
sumPerRoom = (thesum * <?php echo $searchQueryNumOfDays;?>);
formatedSumPerRoom = sumPerRoom.toFixed(2);
$('.newprice').append(thesum +" € x Evenings: <?php echo $searchQueryNumOfDays ;?> = "+formatedSumPerRoom+" €");
});
// above part work just fine, problem is bellow.
//I guess that bellow I should try something with child div
//but i don't know how to do it
$(".box").click(function(){
var sum = 0;
$('.specialprice2').each(function(i, el) {
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
});
alert(thesum);
});
Needles to say the sum alert the sum of all divs, and i want only the clicked ones.
If someone can help me to alert or to console log the updated price, I will find my way from there.
Regards, John
$('.box').on('change', function(){
calculate();
});
function calculate(){
var total = 0;
$('.box:checked').each( function(){
var price = parseFloat($(this).next('.specialprice2').text());
total = total + price;
});
alert(total.toFixed(2));
}
calculate();
JSFiddle
NEW: There is whole code that should work properly as far as php will.
var thesum = 0;
$(document).ready(function(){
var sum = 0;
$('.specialprice').each(function(i, el) {
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
});
sumPerRoom = (thesum * <?php echo $searchQueryNumOfDays;?>);
formatedSumPerRoom = sumPerRoom.toFixed(2);
$('.newprice').append(thesum +" € x Evenings: <?php echo $searchQueryNumOfDays ;?> = "+formatedSumPerRoom+" €");
});
$(".box").click(function(){
var thesum = sum = 0; //UPDATE
$('.specialprice2').each(function(i, el) {
if($(this).parent().find(".box").is(":checked")){ //<---
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
}
});
alert(thesum);
});
OLD: This code works perfectly:
$(".box").click(function(){
var thesum = sum = 0; //UPDATE
$('.specialprice2').each(function(i, el) {
if($(this).parent().find(".box").is(":checked")){ //<---
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
}
});
alert(thesum);
});
What it does is getting parent of .specialprice2 element, then finds .box element in it and checks if checkbox is checked.

textbox calculator with parsing function to arithmetic function

What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>
Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}
There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);

JS for each replacement of manual copy function

I am looking for way to automate this selection.
For example, I will have 10 double inputs (20 inputs total) and I don't want to write JS script for each inputs, but simply use each() function (I am open to different ways) and declare only selectors.
JsFiddle: http://jsfiddle.net/vs7fa/
Idea:
var SELECTORS_H = array();
$.each(SELECTORS_H){
$('SELECTOR_H').keyup(function () {
// do magic
$('SELECTOR_V').val(num);
});
$('SELECTOR_V').keyup(function () {
// do magic
$('SELECTOR_H').val(num);
});
}
HTML:
<label for="h_one">H_ONE:</label>
<input type="text" name="h_one">
<label for="v_one">V_ONE:</label>
<input type="text" name="v_one">
There will be more of inputs. Pattern is:
h_one, v_one
h_two, v_two
h_something, v_something
...
JS:
$(function() {
$('input[name="h_one"]').keyup(function() {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
}
else {
var num = Math.abs(one) * 1;
}
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function() {
var two = $(this).val();
if (two > 0) {
var num = Math.abs(two) * -1;
}
else {
var num = Math.abs(two) * 1;
}
$('input[name="h_one"]').val(num);
});
});
You can handle this using a selector with a common class for all your element and data-attributes to know the element and the linked elements.
HTML:
<label>H_ONE:</label>
<input type="text" class="handler" data-id="h1" data-link="v1" />
<br>
<label>V_ONE:</label>
<input type="text" class="handler" data-id="v1" data-link="h1" />
Code:
$(function () {
$('.handler').keyup(function () {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
$('input[data-id=' + $(this).attr("data-link")+']').val(num);
});
});
Demo: http://jsfiddle.net/8KgTk/
may be this...
Jsfiddle: http://jsfiddle.net/vs7fa/3/
$('input[name="h_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="h_one"]').val(num);
});
function DoMagic(element) {
var one = $(element).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
return num;
}
You should be able to perform the .each function by using jQuery and making the items the same class.
such as:
<label class="forElement" for="h_one">H_ONE:</label>
<input class="inputElement" type="text" name="h_one">
<label class="forElement"for="v_one">V_ONE:</label>
<input class="inputElement" type="text" name="v_one">
$('.forElement').each( function() {
//some code
}
You can do this without adding extra attributes if you want.
$(function () {
$('input[name^="h_"], input[name^="v_"]').keyup(function () {
var one = $(this).val();
var num = - one;
var inputType = $(this).attr("name").substr(0,1);
var inputNumber = $(this).attr("name").substr(2);
$('input[name="'+(inputType == 'v' ? 'h' : 'v')+'_' + inputNumber + '"]').val(num);
});
});
However Irvin Dominin aka Edward's solution is quite good.
Here's a sollution that doesn't require extra markup, and doesn't use string concatenation for logic. It uses $.proxy() to get correct scoping.
Fiddle

How do I add a #.## value to a textbox that already has another ##.## value in it only if a checkbox is checked?

I have been trying to figure out how to make it so that if a specific checkbox is checked, the total amount in a textbox gets 50.00 added to it when the submit button is clicked, before it submits the form. In fact, it would be better to have the update happen as soon as the checkbox is checked.
Here's what i tried so far:
<!DOCTYPE html>
<html>
<head>
<script>
function toggle(){
var indoorCamping = 50.00;
var total = 0.00;
if(document.getElementByName('fifty').is(':checked')){
total = (indoorCamping + document.getElementsByName('Amount').value);
document.getElementsByName('Amount').value = total;
}
else{
return;
}
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<input type="checkbox" name="fifty" value="indoor"/>
<label for="Amount">Amount <span class="req">*</span> <span
id="constraint-300-label"></span></label><br />
<input type="text" class="cat_textbox" id="Amount" name="Amount" />
<p id="demo"></p>
<button onclick="toggle()">Click me</button>
</body>
</html>
The value of a text-input is always text (a string) initially. This value needs to be explicitly converted to a number before adding to it, otherwise it concatenates the text. So "20" would become "5020".
Borrowing mohkhan's code:
<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
total = (indoorCamping + document.getElementById('Amount').value * 1);
document.getElementById('Amount').value = total;
}
}
</script>
I've multipled by 1 which is one way to convert "20" to a number. Number(x), parseInt(x) and parseFloat(x) are other ways.
I would prefer to use an object variable though, amt:
<script>
function toggle(checkbox) {
var indoorCamping = 50.00;
var total = 0.00;
var amt = null;
if (checkbox.checked) {
amt = document.getElementById('Amount');
total = (indoorCamping + amt.value * 1);
amt.value = total;
}
}
</script>
Add the click event on the checkbox then. Like this...
<input type="checkbox" name="fifty" value="indoor" onclick="toggle(this);"/>
And then in your script...
<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
total = (indoorCamping + document.getElementById('Amount').value);
document.getElementById('Amount').value = total;
}
}
</script>

Method to sum up all input values always returns 0

Why do I get only zero in my calculation?
Code:
<?php echo 'AU$ <input type="text" name="pay_total" class="amount_text_change" id="amount_textbox_'.$i.'" onChange="UpdateValue_'.$i.'()" onKeyUp="AddInputs()" value="1">'; ?>
<td>Total</td>
<td>AU$ <span id="Display"></span></td>
Javascript:
function AddInputs()
{
var total = 0;
//var coll = document.getElementsByTagName("input")
var coll = document.getElementsByTagName("pay_total")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
This javascript will auto add everytime user enter a numeric value in the textbox, but it's strange, the result is zero, must be something missing, can you help me?
Thanks
This...
document.getElementsByTagName("pay_total")
should be...
document.getElementsByName("pay_total")

Categories

Resources