jQuery Progress Bar Not Working - javascript

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");
}
});

Related

Dropdown with numbers from 1 - 10 and total price below must change

I am trying to create a drop down with numbers from 1 - 10 for example. Once a number is selected, it should change the total amount. However I have not succeeded and not sure what else I should do, please help.
I have got something put together so far.
<div class="checkout">
<input type="number" name="quantity" placeholder="How many would you like to order? (numeric numbers only)" class="quantity price" data-price="49" value="">
<p class="total" style='margin-bottom: 0px;' >Total: <span id="total">R49 per month</span></p>
</div>
<script type='text/javascript'>
$(document).ready(function(){
$(".checkout").on("keyup", ".quantity", function(){
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("R" + price * quantity);
})
})
var foo = document.getElementById('.checkout');
foo.addEventListener('focus', function () {
foo.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
</script>
All I need is to change the type from a number to a drop down.

jQuery to output data value of two checkbox comma separated on another checkbox

Suppose I have two checkbox like these (can be 100 checkboxes as it will be coming in a while loop)
<input type="checkbox" value="20" data="Apple">
<input type="checkbox" value="30" data="Mango">
And I have two textboxes where I want to output values 20+30 = 50 and Apple, Mango.
<input type="text" id="value1"> // to output sum of values i.e., 50
<input type="text" id="value2"> // to output comma separated data values Apple, Mango on select
Here I am able to do the first operation. But I am not sure how to do the second one. what I want is when I check the boxes its sums values and outputs it on 1st text box and when unchecks any box it deducts the values back (its already working as I was able to do it) and the second box should output values Apple, Mango when both boxes are checked respectively. If any box is unchecked say box with data value Mango then the textbox value will become Apple (even comma gets removed) only. How to do this? Here is my currennt jQuery code below for completing the 1st operation. How to do the second one? What else should I add here in this code?
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
$('input:checkbox:checked').each(function(){
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
});
$("#costdisplay").html(total);
$("input[name=amount]").val(total);
});
});
Try this
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
var txt = '';
$('input:checkbox:checked').each(function(){
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
txt += $(this).attr('data')+', ';
});
$("#costdisplay").html(total);
$("input[name=amount]").val(total);
$("#value2").val(txt.slice(0,-2));
});
});
Check if below code works for you!
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
var dataval = "";
$('input:checkbox:checked').each(function(){
var val = $(this).val();
total += isNaN(parseFloat(val)) ? 0 : parseInt(val);
dataval += $(this).attr('data') +", ";
});
$("#value1").val(total);
$("#value2").val(dataval.slice(0,-2));
});
});
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<input type="checkbox" value="20" data="Apple">
<input type="checkbox" value="30" data="Mango">
<input type="text" id="value1"> // to output sum of values i.e., 50
<input type="text" id="value2">
You should use data-* prefixed custom attributes to store arbitrary data, which can be fetched using $.fn.data(key).
$(document).ready(function() {
$('input[type=checkbox]').change(function() {
var $elem = $('input:checkbox:checked'),
$amount = $("input[name=amount]"),
$costdisplay = $("#costdisplay"),
dataValues = [],
total = 0;
if ($elem.length) {
$('input:checkbox:checked').each(function() {
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
dataValues.push($(this).data('value')); //Iterate and populate the array from custom attribute
});
}
$amount.val(total);
$costdisplay.val(dataValues.join(','));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="20" data-value="Apple">Apple<br/>
<input type="checkbox" value="30" data-value="Mango">Mango<br/>
<input type="text" name="amount"> <br/>
<input type="text" id="costdisplay"> <br/>
While calculating the total amount also make string having the data value with comma separator.
Use the below code snippet for it:
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
var data = '';
$('input:checkbox:checked').each(function(){
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
if(data) {
data += ','+ $(this).attr('data');
} else {
data += $(this).attr('data');
}
});
$("#costdisplay").html(total);
$("input[name=amount]").val(total);
$("#value2").val(data);
});
});

How to get an added value from multiple checkboxes in javascript/jquery?

I have multiple checkboxes added with a button. I want to assign a value of 150 for each checkbox that is checked. Maybe my logic is wrong, but i cant get it working. Ideas?
function getValues() {
var cost = 0;
var isChecked = $('.isLab').prop('checked');
$('.isLab').each(function () {
if (isChecked == true) {
cost = 150
}
});
alert(cost);
}
$('button').click(getValues);
function getValues() {
alert( $('.isLab:checked').length * 150 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="isLab"/> Item 1<br/>
<input type="checkbox" class="isLab"/> Item 2<br/>
<input type="checkbox" class="isLab"/> Item 3<br/>
<button>Get values</button>
Comments inline...
function getValues() {
var cost = 0;
$('.isLab').each(function (index, element) {
if (element.checked == true) { // reference current checkbox
cost += 150; // ADD to it!
}
});
alert(cost);
}

Combine multiple input prices to one TOTAL

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.

Javascript increment a value

I have tried and failed trying to get this to work so time to ask the experts.
I've got the following HTML:
<input type="button" value="-" class="minus">
<input type="number" value="20" class="input-text">
<input type="button" value="+" class="plus">
<div class="newprice">
20
</div>
Using javascript (jQuery specific is fine) I need to be able to have it so that when someone clicks the plus button, the number inside the .newprice div gets incremented by 20. Likewise when they hit the minus button the number gets decreased by 20.
Also the same goes for if they use the little up/down arrows on the .input-text field.
Or if they type in a value instead of using any of the buttons, then the number in the .input-text div changes accordingly (if someone typed in 3, the .input-text number would change to 60).
PS: if it's easier the .newprice div can be an text field instead. Whatever works.
[To put this all into context, basically its part of a shopping cart but I am trying to show the user how much they will be paying for the product when they enter a quantity. For example, the product costs $20, and if they want 3 of them they will be able to see straight away (before adding to their cart) that this is going to cost them $60.]
I hope I explained it properly.
Thanks in advance.
You can do this.
// how many to increment each button click
var increment = 20;
$('.plus, .minus').on('click', function() {
// the current total
var total = parseInt($('#newprice').text());
// increment the total based on the class
total += (this.className == 'plus' ? 1 : -1) * increment;
// update the div's total
$('#newprice').text(total);
// update the input's total
$('.input-text').val(total);
});
$('.input-text').on('change', function() {
// update the div's total
$('#newprice').text( $(this).val() );
});
Edit based on comments
// how many to increment each button click
var increment = 20;
$('.plus, .minus').on('click', function() {
// the current total
var total = parseInt($('#newprice').text());
// increment the total based on the class
total += (this.className == 'plus' ? 1 : -1) * increment;
// update the div's total
$('#newprice').text(total);
});
$('.input-text').on('change', function() {
// update the div's total
$('#newprice').text( $(this).val() );
});
To increment the number input by 20, add the attribute step like so. The number in that attribute represents how much the value will be incremented each time the up and down buttons are pressed.
<input type="number" value="20" step="20" class="input-text">
I already add some calculation and html for handle the basic price. See demo in jsfiddle
HTML:
Price per item:<input name="basicPrice" value="20" class="input-text">
<br />
<input type="button" value="-" class="minus">
<input name="quantity" id="quantity" type="number" value="1" class="input-text">
<input type="button" value="+" class="plus">
<br />Money much pay:
<span class="newprice">20</span>
JS by jquery :
function calculate(){
var basicPrice = parseInt($(":input[name='basicPrice']").val());
var quantity = parseInt($(":input[name='quantity']").val());
console.log(quantity);
var total = basicPrice * quantity;
$(".newprice").text(total);
}
function changeQuantity(num){
$(":input[name='quantity']").val( parseInt($(":input[name='quantity']").val())+num);
}
$().ready(function(){
calculate();
$(".minus").click(function(){
changeQuantity(-1);
calculate();
});
$(".plus").click(function(){
changeQuantity(1);
calculate();
});
$(":input[name='quantity']").keyup(function(e){
if (e.keyCode == 38) changeQuantity(1);
if (e.keyCode == 40) changeQuantity(-1);
calculate();
});
$(":input[name='basicPrice']").keyup(function(e){
calculate();
});
var quantity = document.getElementById("quantity");
quantity.addEventListener("input", function(e) {
calculate();
});
});
Let's me know if you need any support.
You can do...
var $counter = $('.counter');
$('button').on('click', function(){
var $button = $(this);
$counter.text(function(i,val){
return +val + ( $button.hasClass('up') ? 1 : - 1 );
});
});
with this HTML...
<div class="counter">10</div>
<button class="down">-</button>
<button class="up">+</button>
For the record, you should definitely be using an input for the counter element.
Here's your pure JS example but I believe to catch anything below IE9 you'll have to attach event listeners as well.
jsFiddle
<form>
<input type="button" id="value-change-dec" value="-">
<input type="text" id="new-price" value="0" disabled>
<input type="button" id="value-change-inc" value="+">
<br>
<input type="number" id="change-price">
</form>
document.getElementById("value-change-dec").addEventListener("click", function() {
var value = parseInt(document.getElementById('new-price').value);
value=value-20;
document.getElementById('new-price').value = value;
});
document.getElementById("value-change-inc").addEventListener("click", function() {
var value = parseInt(document.getElementById('new-price').value);
value=value+20;
document.getElementById('new-price').value = value;
});
function changeIt() {
document.getElementById('new-price').value = document.getElementById('change-price').value*20;
}
var changer = document.getElementById('change-price');
changer.addEventListener('keydown', changeIt, false);
changer.addEventListener('keyup', changeIt, false);
changer.addEventListener('click', changeIt, false);

Categories