Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone
Related
I'm building a donate modal.
When I click on the donate button, the progress bar gets incremented based on the input value.
I want to replace the money string from h1 when I click on donate.
So if the input value is 10, when I click on the donate button the h1 should read:
$140 is still needed for this project
This runs only once, because it replaces the text only when it finds '$150'.
.modal
.modal-header-box
h1 $150 is still needed for this project
.modal-content
progress#myProgress(value='50', max='200')
h1 Only days left to fund this project. Join the other 42 other donors who have already suppoorted this project. Every dollar helps.
input(type='number', placeholder='$' id='value', max='100')
button#btn Give Now
.button.save-later Save for later
.button.social Tell your friends
JavaScript
document.getElementById('btn').addEventListener('click', function() {
var x = document.getElementById('myProgress');
console.log(x.value, document.getElementById('value').value)
x.value = +x.value + +document.getElementById('value').value;
let difference = x.max - x.value;
console.log(difference);
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
});
Is there any way to make this more dynamic, so the string will update If click on the donate button multiple times?
CodePen link
https://codepen.io/make96/pen/XWZdbPZ
Your problem resides in replacing everything on the page. You should restrict the transformation to the elements that you are changing.
Instead of replacing document.body, then target the modal header box instead.
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
Replace the modal-header-box content instead.
document.getElementsByClassName("modal-header-box")[0].innerHTML = `<h1>$${difference} is still needed for this project</h1>`;
Just put the number in a span and only change the span input on every click.
You take the value of the span and the value of the input box and substract it everytime you click on it.
Function:
document.getElementById("btn").onclick = function(){
var value = parseInt(document.getElementById("test").innerHTML);
var donate = parseInt(document.getElementById("value").value);
document.getElementById("myProgress").value += donate;
document.getElementById("test").innerHTML = value-donate;
}
modal-header-box
.modal-header-box
h1 $<span id="test">150</span> is still needed for this project
Don't replace the document body, Not good practice to update the body every time, update only the required field.
Javascript
document.getElementById("btn").addEventListener("click", function() {
const title = document.getElementById("title");
const x = document.getElementById("myProgress");
const prev = +x.value
x.value = prev + +document.getElementById("value").value;
let difference = x.max - x.value;
title.innerHTML = title.innerText.replace(x.max - prev, `${difference}`);
});
Template
h1#title $150 is still needed for this project
I am trying to create several checkboxradio buttons groups in jQuery mobile that depend on a limit checkboxradio button group value. For example if a limit of 6 is selected I want to only allow the user to be able to select up to a total of 6 children based on all of the other checkboxradio button group selected values and disable everything else. When the limit changes I want to update the UI accordingly.
I have the following code in my change event handler whenever any of the checkboxradio buttons are clicks:
function updateUI(element) {
var limit = parseInt($('input[name="Limit_Total"]:checked').val(), 10);
// Children
var childCount = parseInt($('input[name="Child_Total"]:checked').val(), 10);
var secondChildCount = parseInt($('input[name="Second_Child_Total"]:checked').val(), 10);
var thirdChildCount = parseInt($('input[name="Third_Child_Total"]:checked').val(), 10);
var fourthChildCount = parseInt($('input[name="Fourth_Child_Total"]:checked').val(), 10);
var fifthChildCount = parseInt($('input[name="Fifth_Child_Total"]:checked').val(), 10);
// Totals
var totalChildern = childCount + secondChildCount + thirdChildCount + fourthChildCount + fifthChildCount;
// Enable the correct combination of children
$('input[name*="Child_Total"]').not(element).checkboxradio('disable').checkboxradio('refresh');
for (var i = 0; i <= 6; i++) {
if (i <= (limit - totalChildren)) {
$('input[id$="Child_Total_' + i + '"]').not(element).checkboxradio('enable').checkboxradio('refresh');
} else {
$('input[id$="Child_Total_' + i + '"]').not(element).attr('checked', false).checkboxradio('refresh');
}
}
}
I basically want to simulate the behavior illustrated in the image below:
The problem is it doesn't quite give me the behavior I want. It deselects all but the button I select within the group. I am trying to figure out the most efficient way to do this but I am having a hard time. Any suggestions or help would be greatly appreciated!
I have setup the following jsfiddle to demonstrate the UI: http://jsfiddle.net/X8swt/29/
I managed to solve my problem with the following function:
$('div fieldset').each(function() {
// Disable all none checked inputs
$(this).find('input:not(:checked)').checkboxradio().checkboxradio("disable").checkboxradio("refresh");
// Grab the selected input
var selectedElement = $(this).find('input:checked');
// Calculate the remaining children that can be selected
var remaining = (limit - totalChildern);
// Enable all inputs less than the selected input
$.each($(selectedElement).parent().prevAll().find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
// Enable up to the remaining boxes past the selected input
$.each($(selectedElement).parent().nextAll().slice(0,remaining).find('input'), function() {
$(this).checkboxradio().checkboxradio("enable").checkboxradio("refresh");
});
});
Please feel free to comment or critique my solution.
Here i'm trying to calculate the values based upon the active span. I've posted my full codes on jsfiddle. Span is not contenteditable. And another important thing is i'm assuming span values are 40. So, if user selected the span it would change into green color. if user click another span span#returndata should be 40+40 = 80. if user clicks another span the result should be 40+40+40 = 120.
I've tried below jquery. But i didn't get the result..
JsFiddle
jQuery
$(".text").click(function(){
$(this).toggleClass('selected');
$(function(){
$('span#text').click(function(){
value = 40;
var t = ('span#text').value;
var total = (t+t);
$('span#returndata').val(total);
});
});
});
I updated your jFiddle to make it work. http://jsfiddle.net/m89L4/6/
It is better to recalculate the value everytime a user clicks based upon the number of seats chosen because you may get inconsistencies otherwise.
JS Code
$(".text").click(function(){
$(this).toggleClass('selected');
var count = $('.selected').length;
var value = 40;
$('.returndata').text(value*count);
});
Try this one
$(".text").click(function(){
$(this).toggleClass('selected');
value = 40;
var t = parseInt($(this).text(),10);
var total = parseInt(value+t);
$('span.returndata').text(total);
})
I have been looking for this script everywhere however i was unable to find it. I am trying to create a simple donation count. When a value is added inside a textbox I want it to be permanently fixed into second textbox after button submission. Thanks in advance for all your help.
1) First get the value from textBox1 (assuming id=textbox1)
2) Assign the value to second textbox (assuming id=textbox2)
3) Add the below code in form submission or button click.
document.getElementById('textbox2').value =
document.getElementById('textbox1').value
Try this:
<script>
window.onload = function () {
var textfield6 = document.getElementById('textfield6');
textfield6.value = 0;
document.querySelector('input[type=button]').onclick = function () {
textfield6.value = parseInt(textfield6.value) + parseInt(document.getElementById('textfield5').value);
}
}
</script>
Demo here
Question
I have a form that uses jQuery for magic. On that form is a button Add Account. That button appends fields Account and Amount and also another button Remove Account (which if you can guess, removes those two fields). This all works nicely...
On the same form there is another field Salary, which I would like to compare with the total of all the Amount fields. The problem is when I use jQuery's $.each() to iterate through the Amount fields it only recognizes those fields that were present in the DOM when the page loaded, and not the newly added fields.
How can I iterate through these appended Amount fields? (Or maybe there is a better to do this altogether?)
What I'm doing now:
$(document).ready(function(){
$('#form').on('keyup', '.amount', balanceAmountsWithSalary);
});
var balanceAmountsWithSalary = function(){
var salary = parseInt($('#salary').val(),10);
var total = 0;
$('#accounts .account').each(function(){
var amount = parseInt($(this).find('.amount').val(),10);
total += amount;
});
if (total === salary) {
$('#accounts .account').each(function(){
// Do some stuff to each input.amount located in div.account
});
} else {
$('#accounts .account').each(function(){
// Do some BAD stuff to each input.amount located in div.account
});
}
}
Thanks!
Answer
So it probably would've been more helpful to include the rest of my code at the outset as the problem was a simple error in the add account event. I mislabeled my container class adding an "s" to name of the appended items only. In any case thats for the comments! Posting an example on jsFiddle helped me find this error, so here is the thing in action in case you were wondering.
As HTML code and code of Dynamic adding inputs are not provided, I have edited an existing Fiddler to get total of dynamic added input field.
In this fiddler simple for loop is used to calculate total amount.
Here is a fiddler which might help you.
//button click get total
$('#GetTotal').click( function(event){
var tableID = "NewInvoiceTable";
GetTotalAmount(tableID);
return false;
});
//Get total
function GetTotalAmount(tableID)
{
var i = $('#' + tableID + ' tr').length;
alert("Total Rows -" + i);
var TotAmt = 0;
for(j=0;j<i;j++)
{
TotAmt += parseInt($('#TotalInline-' + j).val());
}
alert("Total Amount - " + TotAmt);
}