So the script starts with an initial value $8.90 and the idea is to add a extra fee depending on the options that are selected, the HTML is divided by 3 sections 1.check-boxes, 2.Select and 3.input(text).
Each section works independently and I'm trying to find a way to combine all 3 sections so the TOTAL can show the final result depending on the options that were selected.
LIVE EXAMPLE
JQUERY:
$(document).ready( function() {
<!-- COUNTRY OPTIONS SCRIPT -->
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
<!-- END COUNTRY OPTIONS SCRIPT -->
<!-- CHECKBOX OPTIONS SCRIPT -->
var start_price = parseFloat($('#subt0').attr('data-original'));
$("#ser1, #ser2").click(function(){
var amountToAdd = 0.0;
$("#ser1, #ser2").each(function() {
if($(this).is(":checked")){
amountToAdd += parseFloat($(this).attr('data-price'));
}
});
$('#subt0').text(parseFloat(amountToAdd+start_price).toFixed(2));
});
<!-- END CHECKBOX OPTIONS SCRIPT -->
<!-- INPUT OPTIONS SCRIPT -->
$(".opts").click(function() {
var amountToAdd = 0.0;
$(this).each(function() {
$("#map_sector").val($(this).attr('data-price'));
amountToAdd += parseFloat($(this).attr('data-price'));
});
$('#subt0').text(parseFloat(amountToAdd+start_price).toFixed(2));
});
<!-- END INPUT OPTIONS SCRIPT -->
});
HTML:
<input name="service1" type="checkbox" id="ser1" data-price="1" value="1" title="Service 1" />
<input name="service2" type="checkbox" id="ser2" data-price="5" value="1" title="Service 2" />
<select id="country">
<option value="AR">Argentina</option>
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="CU">Cuba</option>
</select>
<input name="map_sector" type="text" id="map_sector" value="5" readonly>
<label class="opts" data-price="1">Option #1</label>
<label class="opts" data-price="5">Option #2</label>
<label class="opts" data-price="8">Option #3</label>
<div>TOTAL: <label id="subt0" data-original="8.90">8.90</label></div>
LOOKING FOR THIS RESULT:
If 2 check-boxes selected: $14.90 + Option (USA) selected: $10.00 + Option#2 selected: $5.00: TOTAL: $29.90
I would use AJAX to 'submit' the form to a PHP script that would calc the price and return it as a result. You use AJAX to prevent the default submit and then POST to the form to the PHP page. Use isset() to check the different options and based on either the isset() or the value of the POST variable modify a variable, and then echo that variable at the end of the PHP.
EDIT: IGNORE THE FIRST PART.
This should work for the select and the checkboxes, im not sure how you are handling the labels.
<script>
//ASSIGN CLASSES TO EACH TYPE OF INPUT I.E. <input name="service1" type="checkbox" class="serviceCheckbox" id="ser1" data-price="1" value="1" title="Service 1" />
//ALSO ASSIGN data-price TO SELECT ELEMENTS ( even if it is 0 )
window.originalCost = 8.90; //window is how you explicitly assign global variables.
window.cost = originalCost;
$( document ).on( 'click', '.serviceCheckbox', function()
{
var thisCost = $( this ).attr( 'data-price' );
if ( $( this ).prop( 'selected' ) == true )
{
addCost( thisCost );
}
else
{
subractCost( thisCost );
}
});
$( document ).ready( function()
{
var previousCost;
var currentCost;
$( document ).on( 'focus', '#country', function()
{
previousCost = $( this ).attr( 'data-price' );
});
$( document ).on( 'change', '#country', function()
{
currentCost = $( this ).attr( 'data-price' );
var priceChange = currentCost*1 - previousCost*1;
if ( priceChange > 0 )
{
addCost( priceChange );
}
else
{
subtractCost( priceChange );
}
});
});
function addCost( cost )
{
var currentCost = window.cost;
var finalCost;
cost = parseFloat( cost );
finalCost = window.cost*1 + cost*1;
window.cost = finalCost;
}
function subractCost( cost )
{
var currentCost = window.cost;
var finalCost;
cost = parseFloat( cost );
finalCost = window.cost*1 - cost*1;
window.cost = finalCost;
}
</script>
and then you would have to translate the window.cost variable into the text for the label. Let me know if this works ( might need minor tweaking ) but I believe the logic is sound.
I will divide the logic into two parts to make things manageable and easy to understand.
Elements that are involved in price update would all have data-price so we can pick it up
Elements on click would just place a class on all selected elements and if needed remove class from other elements where switch is needed.
A single function to calculate price.
Please see this
http://jsfiddle.net/farrukhsubhani/Q2XVw/2/
function CalculateTotalPrice() {
var totalPrice = 0.0;
$(".priceitem").each(function(){
totalPrice += parseFloat($(this).attr("data-price"));
});
$("#subt0").html("$" + totalPrice);
}
I have changed your html and js to make things work.
Related
Could anybody help me with this problem? I have an input price value that changes when you select different checkboxes, but it doesn't add up.
I don't really know how to fix it that if you select something, it adds to the total price, and when you select another one it adds again.
The foreach is to get all the exa_names from the Extra table with the checkbox and the price from that item.
Javascript
$(document).ready(function(){
$(".option").change(function(){
var id = $(this).attr('id');
console.log(id);
var id_number = id.split("_")[1];
console.log(id_number);
var hidden_input = $(".option_price" + id_number).val();
console.log(hidden_input);
})
});
HTML
<label>Options</label><br>
#foreach($options as $option)
<div>
<input type="checkbox" class="option" id="option_{{ $option->exa_id }}" name="option_{{ $option->exa_id }}" value="{{ $option->exa_id }}" {{ isset($cache) ? (isset($cache['option_' . $option->exa_id]) ? 'checked' : '') : (old() ? (old('option_' . $option->exa_id) ? 'checked' : '') : ($inschrijving ? (in_array($registration->exa_id, $registration_options) ? 'checked' : '') : '')) }} >
<input type="hidden" value="{{ $option->exa_price}}" class="option_price_{{ $option->exa_id }}">
<label>{{ $option->exa_name }}</label>
<label> €{{ $option->exa_price }} </label>
</div>
#endforeach
Html input totalprice(where it has to show the total price)
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label>Total</label>
<input type="text" name="totalprice" id="totalprice" class="form-control" data-blocked="<>{}" value="0" required>
</div>
</div>
</div>
RegistrationController
$options_ids_array = array();
$options = Extra::all();
foreach($options as $option){
$option->exa_id = "option_" . $option->exa_id;
$input_option = $option->exa_id;
if(!is_null($input_option)){
$options_ids_array[] = $input_option;
}
}
$registration->dev_option_id = implode(",", $options_ids_array);
$registration->save();
I think it's better to store the price of your item in a javascript variable (because it prevent to change the value of hidden input and have easy access on js side) and access to your price through your checkbox value (because it is exactly the id you tried to get with id value by split it with _ character). For add price from checked checkboxes (if they are not too much checkboxes), create a check function to detect which of them are checked and then select the price of each and add them to each other, then put it to your price place. Something like:
var options = $(".option");
var options_price = ['your', 'price', 'values', 'according', 'to', 'options', 'id'];
function optionsPrice() {
var total_price = 0;
options.each(function () {
var option = $(this);
if (option.is(':checked') && option.val() != '' && $.inArray(option.val(), Object.keys(options_price))) {
total_price += options_price[option.val()];
}
});
return total_price;
}
Call optionsPrice function on any checkbox change.
OR if you have a lot of checkeboxes on your page,
you can have a global total price variable and add or sub price from it on any checkbox change. Something like:
var total_price = 0;
var options = $(".option");
var options_price = ['your', 'price', 'values', 'according', 'to', 'options', 'id'];
var option, val;
options.on('change', function() {
option = $(this);
val = option.val();
if(val && val != '' && $.inArray(val, Object.keys(options_price)) !== -1) {
if(option.is(':checked')) {
total_price += options_price[option.val()];
} else {
if(total_price > 0) {
total_price -= options_price[option.val()];
} else {
total_price = 0;
}
}
}
});
I hope it helps :)
You've got the tricky part - uniquely identifying your inputs in JS - already done. All that is left is to sum them up!
The simplest option is to iterate over all your inputs whenever one of them changes, and recalculate the price from scratch.
I'm not 100% sure how your inputs and prices and extra costs work, but let's make it simple. Here's some example HTML in the format your Blade template could generate:
<div>
<input type="checkbox" class="option" id="option_1" name="option_1" value="1" checked>
<input type="hidden" value="1" class="option_price_1">
<label>Orange</label>
<label>1</label>
</div>
<div>
<input type="checkbox" class="option" id="option_2" name="option_2" value="2">
<input type="hidden" value="2" class="option_price_2">
<label>Apple</label>
<label>2</label>
</div>
<div>
<input type="checkbox" class="option" id="option_3" name="option_3" value="3" checked>
<input type="hidden" value="3" class="option_price_3">
<label>Pear</label>
<label>3</label>
</div>
<!-- I've added a total area to display the total result -->
<div id="total"></div>
Now taking your code, and using jQuery's .each() to iterate over all inputs on the page:
$('.option').change(function() {
// This is what we'll use to sum the prices
var total = 0;
// Use .each() to iterate over all .option inputs
$('.option').each(function(index) {
// Inside .each, $(this) represents the current element
var id = $(this).attr('id');
var id_number = id.split("_")[1];
// Note your code was missing the _ after price here
var hidden_input = $(".option_price_" + id_number).val();
// Is this option checked? If yes, we want to add its value to
// the total
if ($(this).prop('checked')) {
// .val() returns a string, prefixing hidden_input with '+' is
// a trick to cast it as a number
total += +hidden_input;
}
console.log(id, id_number, hidden_input, total);
});
// We've processed all inputs and have a total, update our page with
// the result
$('#total').html(total);
});
Done!
The above works fine, but here are some suggestions for minor improvements:
1) Use for on your labels, so that clicking on the text will also toggle the checkbox.
2) It is good practice to cache your jQuery selectors, otherwise jQuery has to parse the DOM each time to look for them. That's trivially unimportant in this example, but it is good practice to get into so you won't get bitten by problems as your pages get more complex.
3) It is good practice to separate your JS code into smaller chunks, so eg have a function that sums up the price, and a separate event handler which simply calls that when an option is changed.
Putting all that together, here's updated code:
<!-- Just one for example -->
<div>
<input type="checkbox" class="option" id="option_1" name="option_1" value="1" checked>
<input type="hidden" value="1" class="option_price_1">
<label for="option_1">Orange</label>
<label>1</label>
</div>
And now the JS:
// Cache your selectors
var $options = $('.option'),
$total = $('#total');
// Event handler, with callable function
$options.on('change', sumInputs);
function sumInputs() {
var id, id_number, hidden_input, price = 0;
$options.each(function(index) {
id = $(this).attr('id');
id_number = id.split("_")[1];
hidden_input = $(".option_price_" + id_number).val();
if ($(this).prop('checked')) {
price += +hidden_input;
}
console.log(id, id_number, hidden_input, price);
});
$total.html(price);
}
I have some number fields set based on a large number of factors in an eCommerce site. I want an option that will clear out those numbers if a radio option is clicked, but then return to their previous numbers if a different radio option is clicked. I have the following code to set the values to 0, but I dont know how to continue for setting them back. My values are defined in several different places, so I can't easily refer to them, but is there a way to read the fields before they're set to 0, and then set them back to their previous state?
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$('#option1').val('0');
$('#option2').val('0');
$('#option3').val('0');
$('#option4').val('0');
}
else if($(this).attr('id') == 'no-option') {
???
}
You can use data-attributes to store the previously entered/selected value:
$('input[type="radio"]').click(function() {
var $optionOne = $('#option1');
var $optionTwo = $('#option2');
var $optionThree = $('#option3');
var $optionFour = $('#option4');
if($(this).attr('id') == 'yes-option') {
$optionOne.data('previous-value', $optionOne.val());
$optionOne.val('0');
$optionTwo.data('previous-value', $optionTwo.val());
$optionTwo.val('0');
$optionThree.data('previous-value', $optionThree.val());
$optionThree.val('0');
$optionFour.data('previous-value', $optionFour.val());
$optionFour.val('0');
} else if($(this).attr('id') == 'no-option') {
$optionOne.val($optionOne.data('previous-value'));
$optionTwo.val($optionTwo.data('previous-value'));
$optionThree.val($optionThree.data('previous-value'));
$optionFour.val($optionFour.data('previous-value'));
}
});
A possible approach would be to always keep your options' previous state in an array.
var previousStates = [];
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$.saveState(); //Save the current state before changing values
$( "option" ).each(function( index ) {
$(this).val('0');
});
}
else if($(this).attr('id') == 'no-option') {
$.restoreState();
}
});
$.saveState = function() {
previousStates = []; //Empty the array
$( "option" ).each(function( index ) {
previousStates[index] = $(this).val();
});
}
$.restoreState = function() {
$( "option" ).each(function( index ) {
$(this).val(previousStates[index]);
});
}
Note: as this method uses indexes to identify options, be careful if you need to dynamically add or remove an option!
Use data-attributes to store the old values, so you can read them later on.
It's better to use a loop to go trough each element, so you don't need to modify it every time a new input field was added.
You can also change the selector to $('input') or anything that suit your needs.
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$('[id^="option"]').each(function(){
$(this).data('oldval', $(this).val());
$(this).val(0);
});
}
else if($(this).attr('id') == 'no-option') {
$('[id^="option"]').each(function(){
$(this).val($(this).data('oldval'));
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input name="clr" type="radio" id="yes-option">
<span>YES</span>
</label>
<label>
<input name="clr" type="radio" id="no-option">
<span>NO</span>
</label>
<div>
<input type="number" id="option1" value="15">
</div>
<div>
<input type="number" id="option2" value="23">
</div>
<div>
<input type="number" id="option3" value="100">
</div>
<div>
<input type="number" id="option4" value="86">
</div>
I need help with get value from checkbox with jQuery.
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
var $this = $( this ),
value = $this.val();
value_array.push( value );
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
If category 1 checked, getting value (correct).
If category 2 checked, getting value (correct).
If category 1 un-checked, getting value again (false, i don't want
it).
If category 2 un-checked, getting value again (false, i don't want
it).
I want like this:
If category 1 un-checked, remove the value from output array.
If category 2 un-checked, remove the value from output array.
Check if checkbox is checked, add value into array if it is, remove if it's not.
$(document).ready(function() {
var value_array = [];
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
if ($this.prop('checked')) value_array.push(value);
else value_array.splice(value_array.indexOf(value), 1);
console.log($.unique(value_array));
$('#out').html($.unique(value_array).join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You don't have to declare an array to begin with (which will pollute your namespace anyway). You can simply select for all the checkboxes, use .filter() to keep those that are checked, and the use .map() to return their values, all done within the callback of the onchange event listener:
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
Note: Remember to chain .get() at the end of .map(), because it will return a jQuery object/collection and you have to convert it into an array.
See proof-of-concept example below:
$(document).ready(function() {
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
$('#out').html(value_array.join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You can just fetch an array of all checked values at once:
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
value_array = $('.radio-group input:checked').map(function() {
return $(this).val();
}).get();
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
JSFiddle
First, you should understand that the "this" value refers to the object that owns the code. In your case, the "this" in
$( document ).on( 'change', '.radio-group input', function(e)
refers to the "document" itself and not the ".radio-group input". Instead you should do the following so that the "this" refers to your checkbox.
var arr = [];
$(".radio-group input").change(function(){
var val = $(this).val();
//push the value into the array if the checkbox is checked
if($(this).prop("checked")==true)
{
arr.push(val);
}
//otherwise, remove the value from the array
else{
//fetch the index of the value in the array
var index = arr.indexOf(val);
//remove that value from the index
arr.splice(index,1);
}
});
All the Functions below are under a $(document).ready(function()) !
First I have an input which you can fade in/out its looks like this:
<form>
<label for="vorname"> Vorname: </label> <input type="text" id="vorname"/></br>
<label for="nachname"> Nachname: </label> <input type="text" id="nachname"/></br>
<label for="alter">Alter:</label> <input type="number" Id="alter"/></br>
<label for="gender">Geschlecht:</label>
<select id="geschlecht">
<option id="Male">männlich</option>
<option id="Female">weiblich</option>
</select>
<input type="button" value="Zurückklappen" id="back"> //fadeOut
<input type="button" value="Absenden" class="send"/> //eventhandler
</form>
Then I have a click handler to make list entries
$('.send').click(function onClick(){
var age = $('#alter').val();
var preName = $('#vorname').val();
var secName = $('#nachname').val();
var gender = $('#geschlecht').val();
list.push ({
alter: age,
vorname: preName,
nachname: secName,
geschlecht: gender,
});
generateList();
stat();
save();
});
But I want an Edit function who takes the selected list entry,
$("#liste").click(function selectList (event) {
var target = $( event.target );
if ( target.is( "li" ) ) {
target.toggleClass('selected');
}
});
To take exactly this ONE (because i cant edit two at once, or can I? Would also be cool) selected Entry to edit it.
THIS is where i need help (the things before are only explanation, finished work there).
$(".edit").click(function (){
var index = $('.selected')
//this where the magic i think should
// happen somehow i must get an Index form the selcted list entry
function edit(index) {
// here fadeIN the form which is shown above.
$( "#block" ).fadeIn(500);
$( "#block" ).animate({width: '54.4%', opacity: '0.8',fontSize: '1.5em'}, 750);
$( "#block" ).animate({height: '40%', opacity: '0.8', fontSize: '3em'}, 750);
//this is my Idea:
//I want to call the already exsiting click function with an Index
//inside the edit function.
//so the function conitnues like this:
$('.send').click(function onClick(index){
var age = $('#alter').val(index);
var preName = $('#vorname').val(index);
var secName = $('#nachname').val(index);
var gender = $('#geschlecht').val(index);
liste[index].push = {
vorname: preName,
nachname: secName,
alter: age,
geschlecht: gender
};
generateList();
save();
});
}
});
I can post the whole Program if requested. it could be that ( or { are missing in this much of a code, but i asusuure you in my Program is everything right.
at the moment it looks like this:
$("#liste").click(function selectList (event) {
var target = $( event.target );
if ( target.is( "li" ) && !$("li").hasClass('selected')) {
target.addClass('selected');
}
else if (target.is( "li" ) && $("li").hasClass('selected')) {
target.removeClass('selected');
}
});
$('.deleteSel').click(function delSelectedEntries () {
alert("Ausgewählte Beiträge wuden gelöscht");
var sel = $('.selected'); //stores the entrys
sel.remove(); // removes only the list entrys temporaly
});
$(".edit").click(function editSelectedEntries(){
var index = $('.selected').attr("index");
edit(index);
});
edit Function:
function edit (index){
$( "#block" ).fadeIn(500);
$( "#block" ).animate({width: '54.4%', opacity: '0.8',fontSize: '1.5em'}, 750);
$( "#block" ).animate({height: '40%', opacity: '0.8', fontSize: '3em'}, 750);
$('#alter').val(list[index].alter);
$('#vorname').val(list[index].vorname);
$('#nachname').val(list[index].nachname);
$('#geschlecht').val(list[index].geschlecht);
$('.send').click(function onClick(){
var age = $('#alter').val();
var preName = $('#vorname').val();
var secName = $('#nachname').val();
var gender = $('#geschlecht').val();
list[index] = {
vorname: preName,
nachname: secName,
alter: age,
geschlecht: gender
};
generateList();
});
I am a jQuery novice and I am trying to build a dynamic jQuery progress bar. What I need to do is offer a series of checkboxes on a page so that when the visitor checks or unchecks a checkbox it will increase or decrease the value shown on the progress bar. In addition, I need to alert the visitor when they have reached the maximum amount (percentage). Any help would be appreciated. The code below will bind the click event to the progressbar but it doesn't increase or decrease correctly and my max doesn't appear to work?
Here is what I have:
Javascript:
<head>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.18.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#budgetbar").progressbar({ value: 0 });
$(".option1").click(function () {
$("#budgetbar").progressbar({ value: 10 });
});
$(".option2").click(function () {
$("#budgetbar").progressbar({ value: 50 });
});
$(".option3").click(function () {
$("#budgetbar").progressbar({ value: 20 });
});
$(".option4").click(function () {
$("#budgetbar").progressbar({ value: 50 });
});
$("#budgetbar").progressBar({ max: 100, textFormat: 'fraction', callback: function(data) { if (data.running_value == data.value) { alert("Budget limit reached!"); } }} );
});
</script>
</head>
HTML:
<body>
<div id="budgetbar"></div>
<div>
<input type="checkbox" class="option1" />Expense 1 - $100,000<br />
<input type="checkbox" class="option2" />Expense 2 - $500,000<br />
<input type="checkbox" class="option3" />Expense 3 - $200,000<br />
<input type="checkbox" class="option4" />Expense 4 - $500,000<br />
* Max Expenses - $1,000,000
</div>
Try to store the value of the progress bar on a variable, that way you can increase or decrease its value to have the right calculation.
it will be something like:
previousValue = 0;
$("#budgetbar").progressbar({
value: 10+previousValue
});
Also, you need to check if the checkbox is checked, and not use the "click" event. Try something like this
if($('#checkboxId').is(':checked'))
Or course, you need to add an id to your checkboxes.
Hope it helps!
Here you go, hope it helps.
Cheers.
<script type="text/javascript">
$( document ).ready( function()
{
$( "#budgetbar" ).progressbar();
});
var currentProgress = 0;
function adjustProgress( checkbox )
{
if ( $( checkbox ).is( ":checked" ) )
{
currentProgress += parseInt( $( checkbox ).val() );
}
else
{
currentProgress -= parseInt( $( checkbox ).val() );
}
$( "#budgetbar" ).progressbar( "option" , "value" , currentProgress )
if ( currentProgress > 100 )
{
alert( "You have exceeded the maximum value of 100" );
}
}
</script>
<div id="budgetbar"/>
<div>
<input type="checkbox" class="option1" value="10" onclick="adjustProgress( this )"/>Expense 1 - $100,000<br/>
<input type="checkbox" class="option2" value="50" onclick="adjustProgress( this )"/>Expense 2 - $500,000<br/>
<input type="checkbox" class="option3" value="20" onclick="adjustProgress( this )"/>Expense 3 - $200,000<br/>
<input type="checkbox" class="option4" value="50" onclick="adjustProgress( this )"/>Expense 4 - $500,000<br/>
* Max Expenses - $1,000,000
</div>
You can simplify your code quite a bit if you assign values to your input checkboxes:
<input type="checkbox" class="option" value="10"/> Expense 1 - $100,000<br />
<input type="checkbox" class="option" value="50"/> Expense 2 - $500,000<br />
<input type="checkbox" class="option" value="20"/> Expense 3 - $200,000<br />
<input type="checkbox" class="option" value="50"/> Expense 4 - $500,000<br />
This way, you don't have to handle each checkbox differently. Instead you can use a single handler for all of your options. This makes debug and code maintenance a lot simpler.
Secondly, as each option changes, you want to assign the total value to the progressbar, not just the clicked option's value. Use change instead of click, as this will only fire when a checkbox changes its state. (Minor difference, I know).
// The only handler you need:
$('.option').on('change', function() {
// The total
var total = 0;
// Sum the value of all checked checkboxes
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
// Assign the value using the correct method:
$("#budgetbar").progressbar("value", total );
});
Also, you are using progressBar on your call to set the parameters (note the capital B). The correct name is progressbar.
Example: http://jsfiddle.net/DjWCz/2/
HTML: (note the class name change and value addition)
<input type="checkbox" class="option" value="10"/> Expense 1 - $100,000<br />
<input type="checkbox" class="option" value="50"/> Expense 2 - $500,000<br />
<input type="checkbox" class="option" value="20"/> Expense 3 - $200,000<br />
<input type="checkbox" class="option" value="50"/> Expense 4 - $500,000<br />
SCRIPT:
<script type="text/javascript">
$("#budgetbar").progressbar({
value: 0,
max: 100,
textFormat: 'fraction',
complete: function(event, ui) {
alert("Budget limit reached!");
}
});
$('.option').on('change', function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
$("#budgetbar").progressbar("value", total );
});
</script>
You can change the value of jQuery UI progress bar by using
$("#budgetbar").progressbar("option", "value", 25);
This only sets the value to 25 (not increases by 25). To get the value you can use
$("#budgetbar").progressbar("option", "value");
And you are probably going to need to check if the checkbox is checked :-)
I would do it like this (not tested)
var $budgetbar = $("#budgetbar"); // It's no good to repeat selections
$(".option1").click(function () {
var thisValue = 25, // This checkbox' value
currentValue = $budgetbar.progressbar("option", "value"),
newValue;
if($(this).is(':checked')) {
newValue = currentValue + thisValue; // add
} else {
newValue = currentValue - thisValue; // subtract
}
$budgetbar.progressbar("option", "value", newValue)
});
Edit, the alert (there may be a better way):
$budgetbar.bind("progressbarchange", function(event, ui) {
var value = $budgetbar.progressbar("option", "value");
if (value > 100) {
alert("You're over 100");
}
});