I have a simple form has two field with ids = "q9" , "q10" and one button named post , i put total number in "#q9", I am trying to code a progress bar that will be updated based on the count entered in "#q10" when user click post button. https://jsfiddle.net/v756hkd2/10/
//jquery Code
$(document).ready(function(){
$(".postbtn").click(function(){
var curStatus = $('#q9 input').val();;
var startCount = $('#q10 input').val();
$("#q9 input").change(function(){
var progress = (curStatus / startCount) * 100;
$("#myBar").width(progress);
});
});
});
I think the problem is that you use change event listener in the click event listener.
Code is waiting for the #q9 input to change, but I guess you have already set it and you just need to use it.
Maybe something like this would work?
$(document).ready(function(){
$(".postbtn").on('click', function() {
var progress = ($('#q9').val() / $('#q10').val()) * 100;
$("#myBar").width(progress);
});
});
EDIT:
I am not sure if I understood correctly. But it seemed like you fill change the #q9 input value automatically after post.
So I made a solution based on that this input value will change automatically and the change event will occur.
$(document).ready(function(){
$(".postbtn").on('click', function() {
// this is because after click the first label would appear
var currentCount = $('#q9').val();
var progress = (currentCount / $('#q10').val()) * 100;
$("#myBar").width(progress + '%');
$("#label").text(progress + '%');
// then you start to listen the change of the current count input
$('#q9').on('change', function(e) {
currentCount = $(e.target).val();
progress = (currentCount / $('#q10').val()) * 100;
// and change it accordingly
$("#myBar").width(progress + '%');
$("#label").text(progress + '%');
});
});
});
A few notes:
1) $('#q9 input') won't work because it thinks that element with id #q9 has a child input, so I used $('#q9'), or you can use, like someone noted $('input#q9')
2) You can also use methods .change or .click. I just prefer using .on. :)
EDIT: I changed a bit the solution again. And added jsfiddle. It should work now - https://jsfiddle.net/v756hkd2/11/
And more beautiful code would be
$(document).ready(function(){
$(".postbtn").on('click', function() {
// this is because after click the first label would appear
changePercentage($('#q9').val());
// then you start to listen the change of the current count input
$('#q9').on('change', function(e) {
changePercentage($(e.target).val());
});
});
// then there won't be repeated code ;)
function changePercentage(currentCount) {
var progress = (currentCount / $('#q10').val()) * 100;
$("#myBar").width(progress + '%');
$("#label").text(progress + '%');
}
});
You don't need to listen to input's change event, if you want to update progress when pressing Post button. It's easier to listen to Post button click. Also values inside inputs are strings, so you have to convert them to numbers before calculation.
function getInputValue(selector) {
var str = $(selector).val();
return parseInt(str, 10);
}
function updateProgress() {
var total = getInputValue('#q10');
var current = getInputValue('#q9');
var progress = (current / total) * 100;
//if you want to limit number of digits after decimal point
//progress = progress.toFixed(2);
$("#myBar").css("width", progress + "%");
$("#label").text(progress + "%");
}
$(function() {
$(".postbtn").click(updateProgress);
updateProgress();//if you want to render outside of click handler, for example after page load.
});
https://jsfiddle.net/yevt/ne1k7w03/2/
Related
I have a large button on the left and a form on the right. When you click the button on the left it allows you to create 6 forms in total. That is the set limit and you can not go over it.
Problem #1 - If you select the X icon to delete one of the clones. And then begin adding more clones again. It breaks the set clone limit 1-6 and allows you to create infinite clones.
Problem #2 - How do i remove the X Icon from the first/initial form and only have it "allowed" on its clones.
Thanks!
JS FIDDLE
JS
var clones_limit = 5;
var cloned_nbr = $(".clonedInput").length-1; //Exclude Default (first) div
function clone()
{
if(cloned_nbr<clones_limit)
{
cloned_nbr++;
var new_clone = $(".clonedInput").first().clone();
$("#formy").append(new_clone);
rearrange();
}
}
function remove(){
$(this).parents(".clonedInput").remove();
cloned_nbr--;
rearrange();
}
function rearrange(){
var count = 1;
var totalCount = $(".clonedInput").length;
$(".clonedInput").each(function(){
$(this).attr("id", "clonedInput"+count).find(".label-nbr").text(count).end().
find(".category").attr("id","category"+count).end().find(".remove").toggle(totalCount!=1).attr("id","remove"+count).on("click", remove);
count++;
});
}
$(".clone").on("click", clone);
$(".remove").on("click", remove);
The problem was with the way you were attaching click event for .remove element. since you were attaching it on create, it used to trigger remove for all the elements recreated and hence decreasing the count of cloned_nbr back to 0. So just remove the click event attaching and make use of event delegation.
Faulty code
function rearrange() {
var count = 1;
var totalCount = $(".clonedInput").length;
$(".clonedInput").each(function() {
$(this).attr("id", "clonedInput" + count).find(".label-nbr").text(count).end()
.find(".category").attr("id", "category" + count).end().find(".remove")
.toggle(totalCount != 1).attr("id", "remove" + count).on("click", remove);
//^^^this was causing the issue
count++;
});
}
Below is the changes, you need to do.
Updated Code
function rearrange() {
var count = 1;
var totalCount = $(".clonedInput").length;
$(".clonedInput").each(function() {
$(this).attr("id", "clonedInput" + count).find(".label-nbr").text(count).end()
.find(".category").attr("id", "category" + count).end().find(".remove")
.toggle(totalCount != 1).attr("id", "remove" + count);
//^^^No need to attach here
count++;
});
}
$(document).on("click", ".remove", remove);//Event delegation
UPDATED FIDDLE HERE
UPDATE - 1
For Problem - 2 Just add below CSS
div[id^="clonedInput"]:first-child .remove{
display:none;
}
UPDATED FIDDLE 2
I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when click changes the amount to $5. I'm trying to get get it so that when the user changes the amount from 5 that it changes the amt = to user input.
The bit of script that changes it
function setDonrAmount(id){
var amt = id.substring(10);
if( amt == 'Other' ){ amt = 5}
var others = id.substring(0,10);
$("button[id*="+others+"]").removeClass('active');
$('button#'+id).addClass('active');
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp
I've made a few updates to setDonrAmount() to handle custom donations.
$("#donrAmountButtons").on("click", function() {
var amt = id.substring(10);
setDonrAmount(amt);
$('#donrAmount' + amt).addClass('active');
});
$("#donrAmountInput").on("focusout", function() {
setDonrAmount($("#donrAmountInput").val());
$('#otherAmount button').addClass('active');
});
function setDonrAmount(val) {
var amt = val || 0;
if (amt.length < 2 && amt < 5)
amt = 5;
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
$('#donrAmountButtons .active').removeClass('active');
}
You'll want to check for a keyup event on the input field, and make the selection when that happens. Something like... (inside document.ready)
$('#donrAmountInput').on('keyup', function() {
// Probably best to strip any non-numeric characters from the field here
amt = $(this).val();
// pseudo-code: $('#donrAmountOther').select(); as I'm not sure about jQuery's handling of input group buttons. There'll be a way to select this one somehow!
});
I have a textarea on which I want to increase his height with one row on every enter and on each time when text it goes into another row wile typing. So I have 3 conditions, when is displayed I want to number all used rows and set rows height based on this:
one: var countRows = $("textarea").val().split(/\r|\r\n|\n/).length;
two: when keypress == 13 is used
and three: when text it goes into another row wile typing
Till now I have achived this but is not really working :|
var countRows = $("textarea").val().split(/\r|\r\n|\n/).length;
var keynum = 13; //enter keynum
//for default state
//not calculating
$("textarea").attr("rows", countRows + 1);
//for enter key
//not really working
$("textarea").on('keypress', keynum, function() {
$(this).attr("rows", countRows + 1);
// alert("jjj");
});
//for case whentext it goes into another row wile typing
I just want to do that using .attr() and updating that attribute "rows" when one more row is added or removed.
From https://stackoverflow.com/a/10080841/4801673
$("textarea").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});
$('textarea').keyup(function(e) {
var $lineHeight = $(this).height() / $(this).get(0).rows;
var $lines = $(this).val().split(/\r|\r\n|\n/).length;
$(this).get(0).rows = $lines;
});
Increase size if add new lines to textarea.
Decrease size if remove lines from textarea.
Nothing to do if lines not added/removed in textarea.
I've got a variable called "widthz" that determines the css width for .progress
Each instance of "widthz" is unique since it's determined from the contents other "brother" divs to .progress. Right now, my function works perfectly but only if you click on .item. I want this action to take place for every instance of .progress without a user event such as a click.
Current code:
$(document).ready(function() {
$( ".budgets .item" ).click(function() {
var limitz = $(this).children('.limit').html();
var spentz = $(this).children('.spent').html();
var widthz = spentz / limitz * 100 ;
$(this).find('.progress').css('width', widthz + '%');
});
});
Replace the event handler with each to iterate over all of them and keep the this reference
$(document).ready(function() {
$( ".budgets .item" ).each(function() {
var limitz = $(this).children('.limit').html();
var spentz = $(this).children('.spent').html();
var widthz = spentz / limitz * 100 ;
$(this).find('.progress').css('width', widthz + '%');
});
});
I am using following code to update one textbox value txtUnitPrice based on other textbox txtQuantity ,both can be generated dynamically which is done.
//update unitprice based on quantity of product and tax applied
$('input').live('keyup', function () {
var inputId = $(this).attr('id'); //get textbox txtQuantity id
var rowNum = parseInt(/txtQuantity(\d+)/.exec(inputId)[1], 10); //get row id
var productValue = $("#ddlProduct" + rowNum).val();
var taxValue = $("#ddlTax" + rowNum).val();
var unitPriceValue = $("#txtUnitPrice" + rowNum).val();
var quantityValue = $("#txtQuantity" + rowNum).val();
if ((quantityValue != " ") && (quantityValue > 0)) {
$("#txtUnitPrice" + rowNum).val(unitPriceValue * quantityValue);
}
else {
$("#txtUnitPrice" + rowNum).val(unitPriceValue);
}
});
Now problem arising in the code above is that when I even moving cursor forward or backward in the textbox txtQuantity then the value for txtUnitPrice is changing becuase which this event 'keyup' is firing and hence whole code is executed with the existing txtunitprice value and multiplies this again with the existing txtquantity which I dont' want Please can anyone help me regarding this . Thanks
Just add a check to ignore the cursor movements like shown below
$('input').live('keyup', function (e) {
if([37, 38, 39, 40].indexOf(e.which)){
return false;//do nothing because the cursor keys have been pressed
}
//the rest of your code
});