finding some based on checkbox and select - javascript

i am trying to find SUM of some number based on check box and select option .
here is my code
<div class="container">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label>
<input type="checkbox" value="10">10
</label>
</div>
<input id="total" placeholder="total" />
And my script is
function updateTotal(){
var total = 0;
$(".container input[type='checkbox']").each(function(){
if($(this).is(":checked")){
var multiplier = Number($(this).parent().prev().val());
var checkboxAmount = Number($(this).val());
total += multiplier * checkboxAmount;
}
});
$("#total").val(total);
}
$("select, input[type='checkbox']").on("change", updateTotal);
The above script is just working fine give html code . But when keep my checkbox first and select option next , then this script will not give any output
i wanted my HTML code like this , then script should be work fine for this
<div class="container">
<label>
<input type="checkbox" value="10">10
</label>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<input id="total" placeholder="total" />
any help , code coppied from here

Try this one-
function updateTotal() {
var total = 0;
$(".container").each(function () {
var checkbox = $(this).find("input[type='checkbox']");
var select = $(this).find("select");
if (checkbox.is(":checked")) {
total += Number($(this).find("input[type='checkbox']").val()) * Number(select.val());
}
});
}

Related

Multiply input value with select option data attribute

I have the following code that is not working the way i want it to, apparently, am trying to multiply select option data attributes with input text area values but instead select option value are being used. I need to figure out why its so.
Here is my code;
<input id="count" min="1" value="1" class ="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class ="txtMult" name="txtEmmail"/>
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
$(function(){
$('.txtMult').change(function(){
var p=$(this).parent().parent()
var m=p.find('input.txtMult')
var mul=parseInt($(m[0]).val()*$(m[1]).val()).toFixed(2)
var res=p.find('.multTotal')
res.html(mul);
var total=0;
$('.multTotal').each(function(){
total+=parseInt($(this).html());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(function() {
calcVal();
});
function calcVal(){
$(this).data('cubics')*$('.multTotal').html();
$("#grandTotal").html($(this).data('cubics')*$('.multTotal').html())
}
// call on document load
calcVal();
Don't use .html() to get the values, use .text() instead.
You need to get the selected option using this:
$("#grandTotal").html($(this).children(':checked')
$(function() {
$('.txtMult').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val() * $(m[1]).val()).toFixed(2)
var res = p.find('.multTotal')
res.html(mul);
var total = 0;
$('.multTotal').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(calcVal);
function calcVal() {
$("#grandTotal").html($(this).children(':checked').data('cubics') * $('.multTotal').text().trim())
}
// call on document load
calcVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input id="count" min="1" value="1" class="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class="txtMult" name="txtEmmail" />
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
</div>
</div>

Javascript: dynamic calculation input value

I have a simple jquery calculator:
<p class="price" data-base-price="50">$<span>80</span></p>
<select name="s1" class="price-option">
<option value="1" data-price="10">Item 1</option>
<option value="2" data-price="20">Item 2</option>
</select>
<select name="s2" class="price-option">
<option value="1" data-price="30">Item 3</option>
<option value="2" data-price="40">Item 4</option>
</select>
<input type="text" name="price-option-input" id="price-option-input">
Javascript:
$(document).ready(function () {
$('.price-option').change(function(){
var price = parseInt($('.price').data('base-price'));
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
});
});
This calculator is working, but the problem is when I enter value for text input the result in price is not updating dynamically (I need to choose another option in selector for result updating)
You have to add keyUp event
calculate = function(){
var price = parseInt($('.price').data('base-price'));
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
}
$(document).ready(function () {
$('#price-option-input', .price-option').change(calculate);
$('#price-option-input', .price-option').keyup(calculate);
});
I think it´s worth it to explain that change event is fired when you unselect the input, or, in number type, when you use the up/down buttons.
You can add a button to do the computation, triggering the change event.
Example:
$("button").on("click", function() {
$('.price-option').trigger("change");
});
Or, you can listen the keyup event from the input and at the enter key press, do the computation. The question is: when do you want to do the computation? With the answer, listen to the proper event and do the computation.
I believe you just need to use .html because that will set the inner HTML:
$('.price span').html(price);
And for future reference, multi-selectors like that aren't near as efficient as something like this:
$('.price').find('span').html(price);
I have fixed your code and it works fine now http://plnkr.co/edit/pWSEimrKkA200jQK9w5a?p=preview
HTML:
<p class="price" data-base-price="50">$<span>80</span></p>
<select name="s1" class="price-option">
<option value="1" data-price="10">Item 1</option>
<option value="2" data-price="20">Item 2</option>
</select>
<select name="s2" class="price-option">
<option value="1" data-price="30">Item 3</option>
<option value="2" data-price="40">Item 4</option>
</select>
<input type="text" name="price-option-input" id="price-option-input" onchange='updatePrice()'>
JS:
function updatePrice(){
var price = parseInt($('.price').data('base-price'));
console.log(price);
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
}

Html/Javascript form calculation and validation in new page

I'm working on a website project and really need help as I'm new to all this. I'm basically given values to every option in the drop down menu's and make them add together which I've managed. But then I want to the total value from the menus to then be the range for a pseudo random to be a generated and added to the age I input.
When I hit submit I'd like it to calculate all that and display the result on a new page. I want to be able to do all this within javascript and html.
Any help would be greatly appreciated! My coding is below. Thanks so much!
<body>
<form id="form1" action="" method="post" onsubmit="return calcTotal(this)">
<select name=select1>
<option selected="selected" value="0">Chinese Zodiac</option>
<option value="3">Rat</option>
<option value="3">Ox</option>
<option value="4">Tiger</option>
<option value="2">Rabbit</option>
<option value="4">Dragon</option>
<option value="5">Snake</option>
<option value="3">Horse</option>
<option value="3">Sheep</option>
<option value="4">Monkey</option>
<option value="5">Rooster</option>
<option value="3">Dog</option>
<option value="3">Pig</option>
</select>
</select>
<br />
<select name=select2>
<option selected="selected" value="0">Star Sign</option>
<option value="2">Aries</option>
<option value="4">Taurus</option>
<option value="3">Gemini</option>
<option value="4">Cancer</option>
<option value="3">Leo</option>
<option value="2">Virgo</option>
<option value="2">Libra</option>
<option value="3">Scorpio</option>
<option value="2">Sagittarius</option>
<option value="4">Capricorn</option>
<option value="2">Aquarius</option>
<option value="3">Pisces</option>
</select>
<br />
<select name=select3>
<option selected="selected" value="0">Blood Type</option>
<option value="3">O</option>
<option value="2">A</option>
<option value="1">B</option>
<option value="3">AB</option>
</select>
<br />
<select name=select4>
<option selected="selected" value="0">Favourite Colour</option>
<option value="3">Black</option>
<option value="3">Blue</option>
<option value="2">Brown</option>
<option value="2">Green</option>
<option value="3">Orange</option>
<option value="3">Pink</option>
<option value="2">Purple</option>
<option value="4">Red</option>
<option value="2">Yellow</option>
<option value="2">White</option>
<option value="5">Other</option>
</select>
<br />
Age<input name="" type="number" value="" />
<br />
<input name="" type="submit" value="Total" />
<span>Total: </span><span id="result"></span>
</form>
<script type="text/javascript">
function calcTotal(oForm){
var sum = 0;
for(i=0; i < oSels.length; i++){
sum += new Number(oSels[i].value);
}
document.getElementById('result').innerHTML = sum;
return false;
}
window.onload=function(){
oSels = document.getElementById('form1').getElementsByTagName('select');
for(i=0; i < oSels.length; i++){
oSels[i].onchange=function(){
document.getElementById('result').innerHTML = '';
}
}
}
</script>
I played with your code. I don't now if it's someting like that that you wanted but here is an example of random score.
It now use the age to generate a value.
Take a look if you like it at my codepen.
I changed the age input:
Age<input id="age" name="" type="number" value="" />
I also added a new function to generate random number between min-max:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
And modified how the sum is calculated:
var age = document.getElementById('age').value;
sum = parseInt(age) + parseInt(getRandomInt(sum-(age / 4),sum+(age / 4)));
//Add some random. The more you are older, the more random it is.
You can do a lot of different generated sum. If you want less modifications, we also can take the last digit of the age to get the min/max value generated...
Edit:
To help you share variables between pages, Look at this question.
Adding this as an answer as the submitter considers it a good idea:
Put the result from all your maths into hidden fields. Then when you submit the form, the values will be passed along.
You don't need to do anything special really. Just add fields like this:
<input type="hidden" value="[yourValue]" name="fieldName" id="fieldId" />
For the yourValue part, simply insert your caclulated value from the JavaScript:
document.getElementById("fieldId").value = calculatedValue;
Since it's all part of the same form that you're submitting anyway, they will all be past along. You can retrieve the fields on the receiving page as normal.
I downloaded and edited your entire code block. I changed a couple of things.
1. You don't need the onsubmit on your form. You need a call the JavaScript function on a Total button. The submit button is added to submit the form when the user is done.
2. A hidden field to hold your result is added to the form.
3. The function where you do your calculation has an addition to send the calulated total to the new hidden field.
4. You need to add something to the ACTION, so it knows where to submit the form. You can also remove the ALERT. I just added that to be sure it worked right.
I've run and tested this, and it works exactly as expected. This is what the edited code looks like:
<body>
<form id="form1" action="" method="post">
<select name=select1>
<option selected="selected" value="0">Chinese Zodiac</option>
<option value="3">Rat</option>
<option value="3">Ox</option>
<option value="4">Tiger</option>
<option value="2">Rabbit</option>
<option value="4">Dragon</option>
<option value="5">Snake</option>
<option value="3">Horse</option>
<option value="3">Sheep</option>
<option value="4">Monkey</option>
<option value="5">Rooster</option>
<option value="3">Dog</option>
<option value="3">Pig</option>
</select>
</select>
<br />
<select name=select2>
<option selected="selected" value="0">Star Sign</option>
<option value="2">Aries</option>
<option value="4">Taurus</option>
<option value="3">Gemini</option>
<option value="4">Cancer</option>
<option value="3">Leo</option>
<option value="2">Virgo</option>
<option value="2">Libra</option>
<option value="3">Scorpio</option>
<option value="2">Sagittarius</option>
<option value="4">Capricorn</option>
<option value="2">Aquarius</option>
<option value="3">Pisces</option>
</select>
<br />
<select name=select3>
<option selected="selected" value="0">Blood Type</option>
<option value="3">O</option>
<option value="2">A</option>
<option value="1">B</option>
<option value="3">AB</option>
</select>
<br />
<select name=select4>
<option selected="selected" value="0">Favourite Colour</option>
<option value="3">Black</option>
<option value="3">Blue</option>
<option value="2">Brown</option>
<option value="2">Green</option>
<option value="3">Orange</option>
<option value="3">Pink</option>
<option value="2">Purple</option>
<option value="4">Red</option>
<option value="2">Yellow</option>
<option value="2">White</option>
<option value="5">Other</option>
</select>
<br />
Age<input name="" type="number" value="" />
<br />
<input name="" type="button" value="Total" onclick="calcTotal();" />
<input name="submit" type="submit" value="Submit" />
<span>Total: </span><span id="result"></span>
<input type="hidden" value="0" name="resultIs" id="resultIs" />
</form>
<script type="text/javascript">
function calcTotal(oForm) {
var sum = 0;
for (i = 0; i < oSels.length; i++) {
sum += new Number(oSels[i].value);
}
//This is what you are using to display the result to your user.
document.getElementById('result').innerHTML = sum;
//This will add the value of the result to a hidden field I added to the form. When you submit it, just request the value of "resultIs"
document.getElementById("resultIs").value = sum;
alert(sum);
return false;
}
//I really don't even see that this is needed. Your form doesn't need to be cleared onLoad.
window.onload = function() {
oSels = document.getElementById('form1').getElementsByTagName('select');
for (i = 0; i < oSels.length; i++) {
oSels[i].onchange = function() {
document.getElementById('result').innerHTML = '';
}
}
}
</script>

JSON Get Request of form Data

I am completely new to JQuery / JSON requests. The code below is the result of 2 days work and I am completely stumped!
Basically I have a form asking for
Number of people
Size of painting
Color of painting (B,C) IE black/white or color
Esentially after selecting the dropdowns then clicking on the color radio button, it will send a JSON request to getdata.php?getIDandPrice=C
What I am trying to achieve is that it will make this request based on the previous entries:
getdata.php?getIDandPrice=1-2x2-C
(ie number of people - size - color)
Appreciate your help
<select id="howmanypeople" name="howmanypeople">
<option value="" selected="selected">Select how many people</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="size" name="size">
<option value="" selected="selected">Select size</option>
<option value="1x1">1x1</option>
<option value="2x2">2x2</option>
</select>
<label><input type="radio" name="getIDandPrice" value="B" id="method2"/>Black & White</label>
<label><input type="radio" name="getIDandPrice" value="C" id="method2"/>Color</label>
<label><input type="radio" name="getIDandPrice" value="B" id="method2"/>Black & White</label>
<div id="post_id"></div>
<div id="_regular_price"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('input[name=getIDandPrice]').click(function() {
MethodTwo();
});
});
//Method 2
document.getElementById('getIDandPrice').value = product(2, 3);
function MethodTwo()
{
$.getJSON("getdata.php?getIDandPrice=C", function(response) {
$('#post_id').html(response.post_id);
$('#_regular_price').html(response._regular_price);
});
}
</script>
Below is the final working code thanks to I Can Has Cheezburger
<!-- http://stackoverflow.com/questions/7191910/loading-json-data-with-jquery-php-and-mysql-for-radio-buttons -->
<select id="howmanypeople" name="howmanypeople">
<option value="" selected="selected">Select how many people</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="size" name="size">
<option value="" selected="selected">Select size</option>
<option value="1x1">1x1</option>
<option value="3x3">3x3</option>
</select>
<label><input type="radio" name="color" value="B" id="color"/>Black & White</label>
<label><input type="radio" name="color" value="C" id="color"/>Color</label>
<div id="post_id"></div>
<div id="_regular_price"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('input[name=color]').click(function() {
MethodTwo();
});
$('select[name=size]').click(function() {
MethodTwo();
});
$('select[name=howmanypeople]').click(function() {
MethodTwo();
});
});
//Method 2
function MethodTwo()
{
//getting the selected value of select#howmanypeople
var people_no = $('#howmanypeople').val();
//getting the selected value of select#size
var size = $('#size').val();
//getting the selected value of select#size
var color = $('#color:checked').val();
//concatenating the values for the URL to look as
//getdata.php?getIDandPrice=1-2x2-C
$.getJSON("getdata.php?getIDandPrice="+people_no+"-"+size+"-"+color, function(response) {
$('#post_id').html(response.post_id);
$('#_regular_price').html(response._regular_price);
});
}</script>
</body>
</html>
If I got it right, you want to pass the value C along with the two select options, you could do it like:
function MethodTwo()
{
//getting the selected value of select#howmanypeople
var people_no = $('#howmanypeople').val();
//getting the selected value of select#size
var size = $('#size').val();
//concatenating the values for the URL to look as
//getdata.php?getIDandPrice=1-2x2-C
$.getJSON("getdata.php?getIDandPrice="+people_no+"-"+size+"-C", function(response) {
$('#post_id').html(response.post_id);
$('#_regular_price').html(response._regular_price);
});
}
In the PHP side, you would have to do something like:
$var = $_GET['getIDandPrice'];
//explode() will break the text at the hyphen `-`
$var_arr = explode("-",$var);
//$var_arr[0] = 1, $var_arr[1] = 2x2, $var_arr[2] = C
Pass the values of the inputs you need to process on the backend:
$.getJSON("getdata.php?getIDandPrice=C",
{
howMany : $('howmanypeople').val(),
size : $('size').val(),
},
function(response) {
$('#post_id').html(response.post_id);
$('#_regular_price').html(response._regular_price);
});
The documentation has several examples:
http://api.jquery.com/jquery.getjson/

sum multiple values from inputs and selects in form

i need to sum the values from multiple SELECTS and INPUTS, this is what i have so far:
HTML
<label>Item#1</label>
<select name="price[]" id="sel_1">
<option value="">Options</option>
<option value="4.00">Small</option>
<option value="8.00">Medium</option>
</select>
<br>
<label>Item#2</label>
<select name="price[]">
<option value="">Options</option>
<option value="4.00">Small</option>
<option value="8.00">Medium</option>
</select>
<br>
<label>Item#3</label>
<select name="price[]">
<option value="">Options</option>
<option value="4.00">Small</option>
<option value="8.00">Medium</option>
</select>
<br>
<label>Item#4</label>
<input type="checkbox" value="1.00" id="price[3]" name="price[]">
<br>
<label>Item#5</label>
<input type="checkbox" value="2.00" id="price[3]" name="price[]">
<br>
<label>Item#6</label>
<input type="checkbox" value="3.00" id="price[3]" name="price[]">
<br> <span id="usertotal"> </span>
JQUERY
$('input:checkbox').change(function () {
var tot = 0;
$('input:checkbox:checked').each(function () {
tot += Number($(this).val());
});
tot += Number($('#sel_1').val());
$('#usertotal').html(tot)
});
$('#sel_1').change(function () {
$('input:checkbox').trigger('change');
});
As you can notice it only sum the value from first select i need it too sum from all the selects.
DEMO: http://jsfiddle.net/B9ufP/
Try this:
(I simplified a bit your code)
(function ($) {
var $total = $('#usertotal');
$('input,select:selected').on('change', function () {
var tot = 0;
$(':checked, select').each(function () {
tot += ~~this.value;
});
$total.html(tot)
});
}(jQuery))
Demo here
If you want to be fancy, you can also use Array.prototype.reduce to sum up the values.
Note that if you have decimals, use parseFloat.
var total = [].reduce.call($('select, :checkbox:checked'), function (pv, cv) {
return parseFloat(pv.value) + parseFloat(cv.value);
});

Categories