Count form inputs - javascript

I have this page (things which I need are at the bottom) and I need to count values from input (type numbers; it's quantity of product) and print value for each product (there are 4 products) and then all values together. Now I'm trying code for count value for each product. I have this Fiddle (code at the end of this post) code, but at my web it doesn't work. And question is why? And next question, after I will have values for each product, how can I pick them from and adding together?
HTML
<input type="number" value="10" class="number rowModre" min="0" name="pocetModre" id="pocetModre">
<div class="cena" id="cenaModre"></div>
JS
var string = $('#pocetModre').val();
$('#cenaModre').html(string);
Thank you very much.

Your question is not quite clear but i guess you are looking for something like this:
http://jsfiddle.net/akpn3/522/
var total = 0;
$(".number").each(function () {
$(".listprice").append("US $" + $(this).val() +"</br>");
total = total + parseInt($(this).val());
});
$(".listprice").append("Total : US $" + total);

Related

second javascript not working on my contact form

Ok, all, I have a few questions.
How can I have my total have a $ and how can I move up next to the word Total: ( so it will be side by side)
Once I get a total price, is there a way where I can divide it by 2 to get 1/2 of the price into another field called 'deposit' before copying that to add to another field called 'balance':
I cannot get the date fields to copy
To note this is where I found how to add up the radio buttons ( Here)
This is what I have so far.
This is my form:
Session Date: <input type="text" name="field1" id="f1" />
Session Type payment :
<input type="radio" name="sessiontypepayment" id="sessiontypepayment1" value="100.00" onclick="FnCalculate(this,'extrapeople');"> Mini Session $100.00
<input type="radio" name="sessiontypepayment" id="sessiontypepayment2" value="250.00" onclick="FnCalculate(this,'extrapeople');"> Full Session $250.00
Extra people :
<input type="radio" name="extrapeople" id="extrapeople1" value="25.00" onclick="FnCalculate(this,'sessiontypepayment');"> 1 person $25.00
<input type="radio" name="extrapeople" id="extrapeople2" value="50.00" onclick="FnCalculate(this,'sessiontypepayment');"> 2 people $50.00
<input type="radio" name="extrapeople" id="extrapeople3" value="75.00" onclick="FnCalculate(this,'sessiontypepayment');"> 3 people $75.00
<input type="radio" name="extrapeople" id="extrapeople4" value="100.00" onclick="FnCalculate(this,'sessiontypepayment');"> 4 people $100.00
Total Amount: <div id="total"></div>
Deposit Amount:
Balance Amount:
balance due BY: <input type="text" name="field2" id="f2" />
This is my script what I have so far.
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>
<script>
function FnCalculate(id,name)
{
var total=0;
if(document.getElementById(name+"1").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
if(document.getElementById(name+"2").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
total = total + parseInt(id.value);
document.getElementById("total").innerHTML = total;
}
</script>
I would really love help on this please.
First, get rid of all the onclick="FnCalculate(this,'xx');" bits on your inputs.
Then replace your <script>s with this:
<script type="text/javascript">
$(document).ready(function() {
$("#f1").keyup(function() {
$('#f2').val($(this).val());
});
var inputs = $('input[name="sessiontypepayment"], input[name="extrapeople"]');
$(inputs).click(function() {
var total = 0;
$(inputs).filter(':checked').each(function() {
total = total + parseInt($(this).val());
})
$('#total').html('$' + total);
$('#deposit').html('$' + (total / 2));
});
});
</script>
Unsure what you mean by "how can I move up next to the word Total" but I suspect changing <div id="total"></div> to <span id="total"></span> will solve your problem. Either that, or apply some css to the div:
#total {
display: inline;
}
I added the calculation for the deposit, you'll need to add <div id="deposit"></div> to your page somewhere...
You will need jquery. Add this in between <head>...</head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First, you should have your defaults set to checked='checked' for HTML radio buttons that you want checked initially. I would put default text into <div id='total'>$125.00</div>, as well. You might as well use jQuery for what it's made for and not put Events into your HTML at all. .val() returns a String. To cast a String to an integer put + in front of it. To cast to a floating point Number use parseFloat().
$(function(){
$('#f1,[name=sessiontypepayment],[name=extrapeople]').change(function(){
$('#total').text('$'+(parseFloat($('[name=sessiontypepayment]:checked').val())+parseFloat($('[name=extrapeople]:checked').val())).toFixed(2));
$('#f2').val($('#f1').val());
});
});
To divide by 2 it's /2
As a newbie you should get into the practice of using external <script src so it will get cached into your Browser Memory, for faster load time when your Client revisits your site.

How do I execute a JavaScript function from clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
<script language="Javascript">
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex)
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex)
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex)
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex)
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex)
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}};
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="var currency = KWD">
<input type="button" value="USD" OnClick="var currency = USD">
<input type="button" value="GBP" OnClick="var currency = GBP">
<input type="button" value="EUR" OnClick="var currency = EUR">
<input type="button" value="CAD" OnClick="var currency = CAD">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="showMeArea.value=finddivid(mktprc,trdval);">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="30">
</html>
If you run this html in your browser you should see what I am trying to achieve.
It is far from complete but here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started 4 days ago!) so would like any like of help that can be offered.
Thanks in advance of your comments.
The first request requires that you put the currency into the actual script, and I would recommend using a setter function:
<script language="Javascript">
var currency; // you might want to set this at a default just in case
function setCurrency(val) { currency = val; } // Setter function
function finddivid(marketprice,tradevalue) {
Then call it in your button click:
<input type="button" value="KWD" onClick="setCurrency('KWD');">
As for the second request, I'd say you have the concept down well enough, but you don't have the method exactly right. First your inputs will need an id attribute:
<input name="mktprc" id="mktprc" input type="number">
<input name="trdval" id="trdval" input type="number">
The name attribute is used for posting values, the id attribute is used by javascript to find elements within a page. Using jQuery would make retrieving these elements easy, but I'll show both the jQuery and the standard JavaScript method of doing this:
jQuery:
<input type="button" value="Calculate" OnClick="$('#showMeArea').val(finddivid($('#mktprc'),$(#'trdval')));">
The $('#id') selects an element. The method .val() sets the value.
Note for the jQuery purists: Yes, there are much better/sophisticated ways to accomplish this with jQuery, but this answer is targeted to my perception of OP's JavaScript capability.
Standard Javascript:
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value = finddivid(document.getElementById('mktprc'),document.getElementById('trdval'));">

Javascript Multiplication and Totals

I have several fields that people will put in loan totals... We'll say loan1 and loan2 just to keep it simple.
window.addEvent('domready', function() {
$('loan1').addEvent('change', rekenen1);
$('loan2').addEvent('change', rekenen1);
});
function rekenen1(){
$('subtotal').value = Number($('loan1').value) + Number($('loan2').value) ;
}
When they enter the data I have it create a subtotal of all the loans. Now I want to make a grand total by taking 1% of the subtotal and adding 295 for the grand total. I need help making this into javascript.
So the equation:
loan1 + loan2 = subtotal
(subtotal*.01)+295=Grandtotal
Thank you for your help!
Provided you have a field with id grandtotal you can just add a line to you rekenen1 function:
function rekenen1(){
var subtotal = Number($('#loan1').val()) + Number($('#loan2').val());
$('#subtotal').val(subtotal);
$('#grandtotal').val(subtotal*0.01+295);
}
Edit:
I gone without saying that the addEvent have to change too:
$().ready(function() {
$('#loan1').addEvent('change', rekenen1);
$('#loan2').addEvent('change', rekenen1);
});
Changed rekenen1 function to use the jquery val function too
changed the event

Calculation using jquery onkeypress

I have this type of exercise in jquery. Go here http://jsfiddle.net/LAntL/3/
For Item 1, if I add #no of quantity of Size 7, it should be multiplied by Item 1's Price displayed in text box and the result should be shown in Item 1's Ext textbox.
then if I do same for size 8.5 of Item 1, it should perform the same.
But the Ext will have (Price x Size 7 Qty) + (Price x Size 8.5 Qty)
Same will happen for Item 2. And along with this, Total quantity and Total price will be updated on keypress event of each textbox.
I'm a beginner in jquery and got this killing exercise.
Please help someone.
Thanks in advance.
I'd suggest that you assign some classes to your fields so that jQuery can easily find them:
"lineQty" - add this class to all the qty fields
"lineTotal" - add this class to all the line total fields
"linePrice" - I think you can see where I'm going with this
"lineExt" - add to all ext fields
Then the following .keyup function will do the updates on all lines automatically.
$(document).ready(function() {
$(".lineQty").keyup(function() {
// 'this' is the field the user is typing in
// so find the tr that it belongs to
var $row = $(this).closest("tr"),
total = 0,
// get the price for the current row:
price = $row.find(".linePrice").val();
// loop through every qty field for the current row and add
// the entered value to the total, using unary plus to convert
// to a number, and a default of 0 if non-numeric data is entered
$row.find(".lineQty").each(function() {
total += +this.value || 0;
});
// set the total for the current row
$row.find(".lineTotal").val(total);
// set the price for the current row
$row.find(".lineExt").val(total * price);
// now add up the grand totals
var grandTotal = 0,
grandPrice = 0;
$(".lineTotal").each(function() {
grandTotal += +this.value || 0;
});
$(".lineExt").each(function() {
grandPrice += +this.value || 0;
});
$("[name='data[totalQuantity]']").val(grandTotal);
$("[name='data[totalPrice]']").val(grandPrice);
});
});
Working demo: http://jsfiddle.net/LAntL/5/ (only works on the first line because I couldn't be bothered assigning classes to all your fields - you would need to add the classes I talk about above to every field as per what I did for the first line).
Okay, you want to learn something, so I will describe a possible way, and don't give you the finished solution.
First of all, you should mark the tables which contains items with class="item". Now you can write a selector in jQuery which gets every item separately. Then you should mark all cells (<td>) which have a special function. Total, Price, Disc and Ext. Your table should look like this:
<table class="item">
<tr>
<td>...</td>
<td class="total">...</td>
<td class="price">...</td>
<td class="disc">...</td>
<td class="ext">...</td>
</tr>
</table>
Now you can write a selector for all input fields inside of the table with class "item".
$('.item input').change(function(){});
Inside of this function you can handle the calculation. At first I would recommend to get the item:
$('.item input').change(function(){
var item = $(this).closest('table.item');
var totalInput = $(item).find('.total input');
var priceInput = $(item).price('.price input');
// ...
var allWriteableInputs = $(item).find('input[readonly!="readonly"]');
// do the calculation
var sum = 0;
$(allWriteableInputs).each(function(i, input){
sum += $(input).val();
});
$(totalInput).val(sum);
});
If you go this way, you don't need:
The onkeypress="return isNumberKey(event);" and
the id="product1Total" for every inputbox
I hope this thought-provoking impulse helps you a little bit. You have still a long way to go, my young padawan ;-)

Filter divs depending on numeric quantity entry

I'm trying to set up a filter using jQuery. I'll have a certain amount of divs, each with a numeric value (let's say price).
I want to have a textbox and button that filters out any divs that are higher than the value given. So for instance, if I enter 10 and hit filter, all divs with a numeric value of 10 or above are hidden.
I can only find filter scripts that are executed via buttons like this, but none of those use a numeric value.
Any help is greatly appreciated. Please bear in mind that my JavaScript skills are limited!
Maybe something like this, iterate thru the each div that has a class of prices
Get the value, parse it as an int, compare it to textbox with the id of myTextBox
$('div.prices').each(function() {
var value = parseInt($(this).text());
if (value >= parseInt($('#myTextBox').val()))
$(this).hide();
else
$(this).show();
})
jsFiddle
Here is the thing:
http://jsfiddle.net/SMPAq/1/
UPDATE:
Ok, here is the whole thing:
<script>
function sortmebaby()
{
var divList = $('#containerMonkey div[id^="monkey_"]');
$.each(divList, function(index, value)
{
console.log($(value).attr('xprice'));
if ( $(value).attr('xprice') > $('#mankipower').val())
$(value).hide();
else
$(value).show();
//alert(index + ': ' + value);
});
}
</script>
<div id="containerMonkey">
<div id="monkey_1" xprice="1">1</div>
<div id="monkey_2" xprice="2">2</div>
<div id="monkey_3" xprice="3">3</div>
<div id="monkey_4" xprice="4">4</div>
<div id="monkey_5" xprice="5">5</div>
</div>
<input type="text" name="mankipower" id="mankipower">
<input type="button" value="PUSH" onclick="sortmebaby()">

Categories

Resources