textbox keyup event not working properly - javascript

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

Related

how to progress bar based on count entered in field using jQuery

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/

Troubleshooting jQuery input value

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

Textarea increase ++ one row on enter and keypress using .attr() update

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.

jQuery traversing and finding textboxes

If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark
Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()
Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});
You could use $(this).closest('input')
Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});

Using custom attribute jQuery selectors with dropdown select (take 2)

This issue is making me want to smash my computer. I have a form, I want to calculate values from selections on the form. I have two jsfiddles here, I really want to have it so I can make selections, then calculate on click. But I can't even get the form to work on click. So the other fiddle uses on change and keyup functions. There is an issue on that form as well. If you change the first select to "option 2", you'll see the value for that select ends up being "1.379999999996" instead of "1.38". Why is this happening?
Fiddle with click function
JS:
$('#submit').click(function(){
var price=$(this).find("option:selected").attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Fiddle with change and keyup functions
JS:
$('#ink, #loc1, .sel').on('keyup change',function(){
var price=$('option:selected', this).attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Your selector $(this).find("option:selected") is wrong as this here points to the #submit button, so you need to find out the select element using its id #style
$('#submit').click(function(){
var price=$('#style').find("option:selected").attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Demo: Fiddle

Categories

Resources