Set Text/Val not appearing in Text Input until clicked/focus (jQuery) - javascript

I have a checkbox which updates totals on a page based on whether it's checked or unchecked. On one part of my form, I would like to zero out a Telerik Numeric TextBox (Text Input field) if the user decides they do not require that category.
When the above checkbox is unchecked, the value in the textbox on the right should change back to zero. To accomplish this, I've written the jQuery code below (note, this function is called whenever something changes on the form):
var zeroValue = getNum(0.00);
//Scaffolding
if ($("#ScaffoldingRequired").attr('checked')) {
scaffoldingCost = getNum($("#ScaffoldingCost").val());
totalCost += scaffoldingCost;
} else {
$("#ScaffoldingCost").val(zeroValue);
$("#ScaffoldingCost").text(zeroValue);
}
//Round&Convert to 'decimal'
function getNum(num) {
var number = parseFloat(num) || 0.00;
var rNumber = Math.round(number * 100) / 100;
return rNumber.toFixed(2) * 1;
}
NOTE: To make sure everything rounds properly and doesn't give me NaN's, I've used my getNum function ( I understand it's a bit hack ).
This code works, and all my totals calculate properly but the textbox does not display a zero value until the user actually clicks on the input box. I've displayed this below:
Is there something I can do to recycle my input box so it displays the zero value immediately? Or am I setting the value/text completely wrong?

You say you're using Telerik, have you considered using their client API for changing the value of the textbox?
var textBox = $('#ScaffoldingCost').data('tTextBox');
textBox.value(0);

Related

How to keep value from re-calculating when you go back in browser?

I have a multi-page form for making reservations which calculates the number of transportation services required based on a few factors. You first choose a number of passengers ('#input_2_6') and Depending on the type of vehicle you choose is how many vehicles you will need, so when you choose a vehicle the "Quantity" field ("#input_2_20") is updated. The on the next page/step, you have to choose if you want a one-way or round trip, so when you choose round trip, the Quantity field is multiplied by two. Then on the next page/step, you are just shown the summary of your order (confirmation page).
The problem is, with the current code, if you are on the confirmation page and decide to go back to the previous page to change something (perhaps you decided you don't want the round trip and only need one-way), the quantity number keeps the new value and now it is multiplied by 2 again when choosing round trip.
jQuery(document).ready(function ($) {
var totalBook;
$('#input_2_12').change(function () {
switch ($(this).val()) {
case 'Escalade|49':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 5);
$("#input_2_20").val(totalBook);
break;
case 'Suburban|0':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 6);
$("#input_2_20").val(totalBook);
break;
case 'Van|14':
$('#input_2_20').val(1);
totalBook = Math.ceil($('#input_2_6').val() / 10);
$("#input_2_20").val(totalBook);
break;
}
});
totalBookNew = $("#input_2_20").val();
$('input:radio[name="input_7"]').change(function () {
$('#input_2_20').val(totalBookNew);
if ($(this).val() == 'Round trip'){
$('#input_2_20').val(totalBookNew);
newTotal = totalBookNew * 2;
$('#input_2_20').val(newTotal);
}
else if ($(this).val() == 'One way'){
$('#input_2_20').val(totalBookNew);
}
});
});
I've tried using the value of 'totalBook' from the first function on the second function but it returns undefined, that's why I created totalBookNew...
I really appreciate any help!
Looks like the main issue is after you do the calculations you set the calculated value into the original input field. Your best bet would be to store the calculations elsewhere in hidden html inputs. So you would have an input called something like:
<input type="hidden" id="input_2_20_calculated" value=0>
Then instead of setting the calculated value back into the input set it in the hidden input instead. Hidden inputs will get passed along with the form, so you would be able to use the calculated values. This is why you get the duplication is because every time the calculation is triggered it's doubling the previous calculated value.
totalBookNew = $("#input_2_20").val();
$('input:radio[name="input_7"]').change(function () {
$('#input_2_20').val(totalBookNew); //This line can be deleted
if ($(this).val() == 'Round trip'){
$('#input_2_20').val(totalBookNew); //You can also delete this line
newTotal = totalBookNew * 2;
$('#input_2_20_calculated').val(newTotal);
}
else if ($(this).val() == 'One way'){
$('#input_2_20_calculated').val(totalBookNew);
}
});
As a cautionary side note you should recalculate on the backend. Don't calculate in the front end and trust those calculations on the back end. It's easy to manipulate the form data on submit and post fake numbers.

Acrobat PDF calculation with checkbox

I've created a PDF form to help create an estimate for plumbing work. There are various lines that the contractor fills in for quanity, cost of the item and then automatically calculates the price for that line; this works fine.
But now I want to add a checkbox to the line that the customer would check if they actually want that work to be done. If they check the box then the price would appear in the final field, otherwise it would display 0.
My fields are:
QtyRow2 ItemCostRow2 CheckboxRow2 PriceRow2
I've tried this Javascript code in the Calculation tab for the PriceRow2 field, but it displays "0" in the price field whether the checkbox is checked or not.
var oFldQty = this.getField("QtyRow2");
var oFldItem = this.getField("ItemCostRow2");
if (this.getField("CheckboxRow2").isBoxChecked(0)) {
nSubTotal = oFldQty.value * oFldItem.value;
} else {
nSubTotal = 0;
}
event.value = nSubTotal;
How should I modify this to get it to work?
If this is the whole code in the calculation, it would be way safer to define nSubTotal; otherwise, it gets defined as a global variable, and can behave strangely.
Also, whenever this calculation runs, and the test results to false, nSubTotal is set to 0. That means, you have to define nSubTotal, and then add to it while you work through the form.
If you want to simply have a result in the field, there is no need to do the detour via a variable; you can set event.value in the true and the false path.
For a single checkbox, it is IMHO easier to use its value (or its "unchecked" value for portability of the code reasons). This leads to the following code snippet:
if (this.getField("CheckboxRow").value != "Off") {
// box is checked
event.value = oFldQtyty.value * oFldItem.value ;
} else {
// box is unchecked
event.value = 0 ;
}
And that should do it.
However, as you have a table, it is best practice to consolidate all calculations into one single script, which can be attached to a hidden read-only field which is not even involved in the calculation itself. This gives you much better overview and control over the calculation, and prevents calculation order errors.

attribute maxlength of input field is changing, but input doesn't care

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.
I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?
my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters(); //this gets called often
EDIT: http://jsfiddle.net/mDw6f/
EDITTTT:
You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)
Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.
Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.
Cheers
Real Fiddle Example
Try using this fiddle:
Working Demo
Use the html input like I did in the code, no need to specify the maxlength attribute to it.
<input type="text" class="my_input_class"/>
and the script
my_var = 25; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters();

using jquery and tablesorter, change the value of a chosen cell

I have a tablesorter table, that fills in correctly. What I am trying to do is to ensure that the cells are not being edited by more than 10% over the original value. For example, if the price field (denoted by id #price) is set to 6.00 in the first cell in the first row, and the next amount is 5.00 in the next row, I want to be able to change either price, or both, but not by more than 10% ( 6 becomes 6.60 for example). here is what I have so far:
$('#tally tr').live ('click', function(){
var tempPrice =0;
tempPrice = $(this).find('#price').val();
// Which selects the correct row and price field and will store that value in tempPrice.
$('#price').change(function(){
var pnew =0;
$('#tally tbody tr').each(function() {
if ($('#price').val() > (tempPrice*1.1)){
pnew = tempPrice*1.1;
$('#price').val(pnew.toFixed(2));
alert("Your cannot raise the price by more than 10%");
}
}); //end of tbody tr function
}); // end of change function
}); // end of new price change function
To change the price and ensure it is not more than the 10%. The functions work to change the first cell, but I cant get the price change function to work if I am changing the second cell. Also, as if this is not complicated enough, if I try to change the second cell first, and then try the first cell, it retains the pnew price from the second cell, and then will update the table with that number (5 as in the example above), then it will update the cell with the correct number (6.60).
How do I get this to work the way I need it to?
EDIT: the price can be lowered as much as the user wants, just not raised by more than 10%.
Firstly you should have 3 variables, one which stores the price, one which is the upper limit (*1.1) and one which is the lower limit (*0.9).
You then need to use $('input').focus() to get the original value and $('input').blur() to run the validation when the user has finished.
The problem is when you have multiple inputs it is hard to keep track of the temp price value as the user could click around, so you need to have a variable which keeps track of the most recent input selector so blur can validate that.
var $current_element;
var temp_price;
var l_price;
var h_price;
$('input').focus(function() {
$current_element = $(this);
temp_price = $(this).value();
});
$('input').blur(function() {
var value = $current_element.value();
h_price = value * 1.1;
l_price = value * 0.9;
// Do validation of prices here and then either alert()
// or set $current_element.value(temp_price)
// If validation fails call $current_element.focus() to return the user there
});
Otherwise check out this option: https://stackoverflow.com/a/10393958/1160747
Oh and as other have mentioned.... ID should be unique to one element, use class for multiple elements!

Check multiple textarea fields for value using jquery and then perform a function

Basically what I'm trying to accomplish is I want to check multiple dynamic forms on a page. Then if All textareas are empty OR have the default value, perform a function. Otherwise if any of them are not empty without the default value, cancel the function.
I know how to get the total count of the divs/forms or go through each one, sorta. Just can't put it together. I want it to check them all first before doing anything.
if (jQuery("div[id^='statuscontainer_']:last").length == 0){
}
I don't think this would get quite what I need to do. Or either I not sure how to form it into the function I need.
Thanks
You could take this approach
Give each input a similar class, in my example, inputBox
Create a script to add the total of each inputBox length. If that total == 0, take whatever approach, otherwise continue with the script
$('#show').click(function() {
var total = 0;
$('.inputBox').each(function() {
total += this.value.length;
});
if (total == 0) {
// Do whatever if it's empty
} else {
// Do whatever if its not
}
});
???
Profit
Try it
http://jsfiddle.net/kLnHC/
Edit
Though, in your application, you'd probably want to change the event that triggers it to $('#yourForm').submit(function() { rather than a click function.
use
total += $(this).val();
instead of
total += this.value.length;
will check if there is only a " " and/or a \n in your textarea.

Categories

Resources