help! onBlur firing before value changed? Wrong values coming from textboxes

Hey developers!

I'm trying to create a clint side system for calculating my total on a line of a purchase order. (i.e. Quantity * Price = lineTotal)  I wanted to do this client side so there were no silly postbacks for such a simple calculation.  I created an onBlur event for the control and linked it to a calculateTotal() method.  Something like this:

.CS code 

txtQty.Attributes.Add(
"onBlur", "CalculateTotal();");

txtPrice.Attributes.Add("onBlur", "CalculateTotal();");

.ASPX code/script

function CalculateTotal() {

 var total = 0.00;

 var qty = parseFloat(document.getElementById("txtQty").value);
 var price = parseFloat(document.getElementById("txtPrice").value.replace("$", ""));

 total = qty * price;

 document.getElementById("txtTotal").value = total;

}

Here's the problem.  When I change a value in either Qty or Price, and the getElementById grabs the value when focus leaves that textbox, it's getting the value of the textbox BEFORE the change occured.  Here's the sequence: 

(1) change txtQty to "4"

(2) CalculateTotal executes and assigns 0 to txtTotal2 (0 qty * 0 price) 

(3) change txtPrice to "10"

(4) CalculateTotal executes and changes txtTotal2 to "0" (4 qty * 0 price)

(5) change qty to "3"

(6) CalculateTotal executes and changes txtTotal2 to "40" (4 qty * 10 price)

You can see how each firing of the event seems to occur before the actual value of the textbox has been changed.  Any reason for this to occur?

 

Thanks for any advice on this.  You'll be my hero if you can solve this one.

0
robertjcallen
8/13/2008 2:45:54 PM
asp.net.client-side 24353 articles. 1 followers. Follow

9 Replies
991 Views

Similar Articles

[PageSpeed] 28

Well, it is doing what you tell it to do -- firing the event when focus leaves the TextBox. I think that your JavaScript needs to look more like this:

<script type="text/javascript">
<!--
function CalculateTotal()
{
 var textBoxQty = document.getElementById('txtQty');
 var qtyValue = textBoxQty.value;
 if ( qtyValue.length <= 0 )
 {
  alert('Please enter a quantity');
  //textBoxQty.focus();
  return;
 }
 
 var textBoxPrice = document.getElementById('txtPrice');
 var priceValue = textBoxPrice.value.replace('$', '');
 if ( priceValue.length <= 0 )
 {
  alert('Please enter a price');
  //textBoxPrice.focus();
  return;
 }
 
 qtyValue = parseFloat(qtyValue);
 priceValue = parseFloat(priceValue);

 document.getElementById('txtTotal2').value = qtyValue * priceValue;
}
// -->
</script>

A better solution would be to place a button to do the calculation rather than using the onblur event of the TextBoxes.

<form id="Form1" method="post" runat="server">
 <input type="text" id="txtQty" />
 <input type="text" id="txtPrice" />
 <input type="button" id="calculateButton" onclick="CalculateTotal();" value="Calculate">
 <input type="text" id="txtTotal2" readonly="true" />
</form>

NC...

0
NC01
8/13/2008 3:34:25 PM

Using a button to do the calculation is not really what I wanted here.  I've seen may sites that use the client side code to perform a calculation like this.  Is there a better client side event I can use that executes once the value has already changed, thus allowing me to get the current value?  I've tried onChange with no success.

I'm using asp controls and in this case, a custom textbox from "Infragistics" (masked to only allow numeric input and auto currency format), but i'm sure the client side events behave the same for it.

0
robertjcallen
8/13/2008 3:44:06 PM

No there is no "magic" event that knows when to do the calculation. Just handle the onblur event on the price TextBox then.

NC...

0
NC01
8/13/2008 3:48:38 PM

I've seen many other sites use onBlur and onChange to do calculations when focus leaves the textbox (i.e. http://www.mcfedries.com/JavaScript/OrderTotals.asp), I think the behavior I'm seeing is irregular and your suggestion that i'm looking for a "magic" event is a little insulting.  Thanks for the effort in trying to help though.

Is there anyone else out there that knows much about onBlur and has seen this sort of delayed value change behavior?

0
robertjcallen
8/14/2008 4:52:14 PM

Ummmm the behavior that you're seeing is not irregular. Think about it. txtQty loses the focus, so the onblur event is fired and attempts to do the calculations with nothing in txtPrice.

NC...

0
NC01
8/14/2008 5:14:51 PM

I'm sorry, I must not have explained my problem correctly.  I understand that the onBlur fires after I leave the txtQty textbox, and of course there's nothing in the txtPrice, so Qty * Price is going to be zero.  The problem isnt there, it's when I leave the txtPrice textbox after updating it.  Lets say I go to the txtQty, set it to "2" and go to the txtPrice and set it to "10".  I'd expect to see a "20" in txtTotal2 but I see a "0" because txtPrice.value is evaluating out to "0".  If after this, I changed the qty again, perhaps to "3", then on firing the onBlur event after the qty loses focus, it finally pulls the value of 10 from txtPrice but it still retains the value of 2 from txtQty.  The problem being that the object that is firing the onblur event is firing the event BEFORE it updates it's value.  I discovered this by putting alerts inbetween each value capture and playing around with it....like so:

function CalculateTotal() { 
 var total = 0.00; 
 var qty = parseFloat(document.getElementById("txtQty").value);  
 var price = parseFloat(document.getElementById("txtPrice").value.replace("$", "")); 
 Alert("Qty : " + qty + ", Price: " + price);
 total = qty * price;
 document.getElementById("txtTotal").value = total;
}

So, I enter qty "2" and the alert says "Qty : 0, Price : 0"
So, I enter price "10" and the alert says "Qty : 2, Price : 0"
So, I enter qty "3" and the alert says "Qty : 2, Price : 10"
See how it's always one step behind?
0
robertjcallen
8/15/2008 2:43:11 PM

Sorry, but I don't get that when I tried it (and I don't see how you do either since Alert gives an object not found error -- should be alert since JavaScript is case-sensitive). Here's the code that I tried:

<form id="Form1" method="post" runat="server">
 <input type="text" id="txtQty" onblur="CalculateTotal()" />
 <input type="text" id="txtPrice" onblur="CalculateTotal()" />
 <input type="text" id="txtTotal" readonly="true" />
</form>

<script type="text/javascript">
<!--
function CalculateTotal()
{
 var total = 0.00;
 var qty = parseFloat(document.getElementById("txtQty").value); 
 var price = parseFloat(document.getElementById("txtPrice").value.replace("$", ""));
 //alert("Qty : " + qty + ", Price: " + price);
 total = qty * price;
 document.getElementById("txtTotal").value = total;
}
// -->
</script>

Here's what I get:

txtQty     txtPrice     txtTotal
------        --------        --------
2                            NaN
2            10            20
3            10            30

NC...

0
NC01
8/15/2008 3:04:56 PM

Yea, I just typed that into the editor here and didnt copy the code from my work.  I'm at home sick today, but trust me, that's the behavior I'm getting.  Always one step behind on the value change. 

Could it be that i'm using an aspx master page and this is a subpage inside a content placeholder?  Does that mess with the firing order or something perhaps?  I've never heard of that but i'm grasping at straws here.  I'm not using any ajax controls on this page, but I do have the binaries imported into this site since they're in use elsewhere.  My only last thought is that the txtQty and txtPrice controls are infragistics (www.infragistics.com) masked textboxes, but I tried this with normal textboxes also and got the same result.  Maybe I should post on their site to see....  Other than that, I've just got a bunch of normal asp controls on the page.

0
robertjcallen
8/15/2008 3:18:30 PM

I don't know. I can't see how any of that could make a difference since all controls have to end up rendering the same in the browser and this is client-side code that will work the same way regardless.

NC...

 

0
NC01
8/15/2008 3:33:03 PM
Reply:

Similar Artilces:

how ontextchanged event in datalist fire and when that textbox value change than another textbox inside datalist value also change
 i have one datalist into which i used maskededit extender for time entry there is three textbox (1) start_time (2) end_time (3) duration so when enter  end_date value than this text box ontextchage event fire and duration will automatically calculate by(end_time - start_time) and display into datalist duration textbox. in datalist there is more than one item.i put some code so just check  <asp:DataList ID="CONTRACT_SERVICE_ITEM" runat="Server" RepeatColumns="1" RepeatDirection="Horizontal"      &nbs...

how to change the value of checkbox when i change the value of textbox
i want the checkbox to change its value to unchecked when the textbox doesnot have anything i.e is value is "" and as soon as i enter anything to it, the checkbox should automatically change to checked. Can you please tell me how to do this Add to the textbox: OnKeyUp="CheckValue()" Add to the html: <script language="javaScript"> function CheckValue() { if (document.getElementById('textboxid').value.length == 0) { document.getElementById('checkboxid').checked = false; } else { document.getElementById('checkboxid').checked...

to change value of Client Side Select html control from database value....
hello forum,  I have a select .. Demo.aspx <select id="DropAccType" name="DropAccType"> <option>Select</option> <option>Saving</option> <option >Current</option> <option>Regular</option> <option>Demat</option> </select> I want to set the value of select by fetching the data from daabase i.e. In my table if I have Value current then when i request the demo.aspx then in select Control the value Current should get selected..... Please help me to sort this out...   Thnx in advance.. Hi-I could be...

Accessing values on the server for controls whose values were changed client-side
Let's say that I have two server controls, a label and a textbox: <asp:Label ID="Label1" runat="server" Text="Old value"></asp:Label> <asp:TextBox ID="TextBox1" runat="server" Text="Old value"></asp:TextBox> Then I run some client-side code that changes their values: document.getElementById('Label1').innerHTML = 'New value'; document.getElementById('TextBox1').value = 'New value'; In the browser, they both visually have the value "New value".  Howev...

How can I set client side values as server side values?
Hi, Can anyone tell me how I can get client side values such as document.referrer, navigator.appName etc... into server side scripts? There are some client side values I'd like to set as session vars and insert into the db? How do I go about this? Thanks for any pointers Davlon PS (I'm using powersite 7.1.0.300) Pass them as page parameters, e.g., http://myserver/myurl?document.referrer=whatever&navigator.appName=yadayada Then, in your server-side script, just loop through the document.value array and get these values. -- pbm_hopethishelps, Roy Kie...

Bug 357684
Name: Ricardo Zorzella Email: zorzellaatsysindotcomdotbr Product: Firefox Summary: Bug 357684 - onchange on textbox not fired when onblur changes text value Comments: In according that link bellow, the problem reported has been "VERIFIED FIXED". But till now (Firefox 2.0.0.7) it persist. Link: https://bugzilla.mozilla.org/show_bug.cgi?id=357684 Best regards. Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; pt-BR; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7 ...

Client side Values to Server values
Hi all, I'm using Visual Studio 2005 and C#.Net  I have one big security problem. I have one web page for user login. When user click in button "Login" i run some functions of javascript for detect pki credentials and i write the credentials in some textboxes. When the login process end, the user must click in another button for redirect the application to another page. I want pass the login credentials to target page, but i can´t use querystrings in url because is not secure ans i don´t want use cookies because some users have disableded cookies. I want...

pass client textbox value to a server side textbox
HiDoes anyone know how in javascript to pass a client side textbox value to a server side textbox?Thanks in advance.Graham. An asp textbox is a resular textbox. so you do it the same way.document.formName.elementName.value = document.formName.elementName2.value;One thing to note is that the asp textbox is going to have a slightly different name then what you named it.EricPascarello.com | Twitter epascarello | LinkedIn...

repeater with textboxes. how to read the textbox values on client side
Hi  I have a data bounded repeater with text boxes attached. How can I read the values of the textboxes using javascript?? Could not find a proper link.. Appreciate any solution , thanks     The repeater will add a prefix to each textboxes ID to ensure uniqueness.  The following function will loop through all textboxes of the repeater, and if the ID of the given textbox contains the string specified, the it will consider it a match and you can access it's value property easily.  Here is the function: function textboxFinder() { var repeater =...

superreview granted: [Bug 357684] onchange on textbox not fired when onblur changes text value : [Attachment 243876] Patch rev. 1
Boris Zbarsky <bzbarsky@mit.edu> has granted superreview: Bug 357684: onchange on textbox not fired when onblur changes text value https://bugzilla.mozilla.org/show_bug.cgi?id=357684 Attachment 243876: Patch rev. 1 https://bugzilla.mozilla.org/attachment.cgi?id=243876&action=edit ------- Additional Comments from Boris Zbarsky <bzbarsky@mit.edu> This looks good to me, but I'd like smaug to check it out. The only worry I have is whether running random script at this point of PreHandleEvent is OK. If it is, then this is great. We'll need a different patch...

superreview requested: [Bug 357684] onchange on textbox not fired when onblur changes text value : [Attachment 243876] Patch rev. 1
Mats Palmgren <mats.palmgren@bredband.net> has asked Boris Zbarsky <bzbarsky@mit.edu> for superreview: Bug 357684: onchange on textbox not fired when onblur changes text value https://bugzilla.mozilla.org/show_bug.cgi?id=357684 Attachment 243876: Patch rev. 1 https://bugzilla.mozilla.org/attachment.cgi?id=243876&action=edit ------- Additional Comments from Mats Palmgren <mats.palmgren@bredband.net> Move the CheckFireOnChange() call from "Blur" to "pre-Blur". ...

How to Encrypt the value of textbox in client side and Decrypt it in server side?
How to Encrypt the value of textbox in client side and Decrypt it in server side? THere is no use in decrypting ur content @ client side since a normal user can view the decrytion logic when he takes 'view source' option 'SSL' technology is used in this situations. SreejithSreejithhttp://tips4dotnet.blogspot.com/ Sreejith: he did not ask to decrypt it on client-side! Take a loot at this article on the Cryptography application block: http://msdn2.microsoft.com/en-us/library/ms954823Josh Stodola ← Come check out my blog! Another good article: http://www.devarticles.com/c/a/VB.Net...

superreview requested: [Bug 357684] onchange on textbox not fired when onblur changes text value : [Attachment 246784] Patch for 1.8 branch
Mats Palmgren <mats.palmgren@bredband.net> has asked Boris Zbarsky <bzbarsky@mit.edu> for superreview: Bug 357684: onchange on textbox not fired when onblur changes text value https://bugzilla.mozilla.org/show_bug.cgi?id=357684 Attachment 246784: Patch for 1.8 branch https://bugzilla.mozilla.org/attachment.cgi?id=246784&action=edit ...

superreview granted: [Bug 357684] onchange on textbox not fired when onblur changes text value : [Attachment 246784] Patch for 1.8 branch
Boris Zbarsky <bzbarsky@mit.edu> has granted superreview: Bug 357684: onchange on textbox not fired when onblur changes text value https://bugzilla.mozilla.org/show_bug.cgi?id=357684 Attachment 246784: Patch for 1.8 branch https://bugzilla.mozilla.org/attachment.cgi?id=246784&action=edit ------- Additional Comments from Boris Zbarsky <bzbarsky@mit.edu> Makes sense ...

Web resources about - help! onBlur firing before value changed? Wrong values coming from textboxes - asp.net.client-side

Notes Plus on the App Store on iTunes
Get Notes Plus on the App Store. See screenshots and ratings, and read customer reviews.

Training - Algodoo
Navigation Home For Fun Algodoo Play Algodoo Physics Scenes Demo Buy For Education Algodoo for Education Lessons User stories Solutions Demo ...


Automated Test Design
... tests along with doing ET. Here's my take on a UI test for Alan's app: Open the page Check that text "Total" exists. Check that the 6 textboxes ...

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 11 Jul 2012

Cyprus By Bus Route Planner - Find your bus journey in Cyprus
Cyprus By Bus route planner for finding the best possible bus route between two bus stops in Cyprus. Based on origin bus stop, destination bus ...

Issues - gwen - GUI system aimed at games - Google Project Hosting
My favorites ▼ - Sign in gwen GUI system aimed at games Project Home Downloads Wiki Issues Source New issue Search Search within: All issues ...

ASP.NET Web Forms DynamicData FieldTemplates for DbGeography Spatial Types
... Those templates are simple. Here's the Edit example. You might say, hang on, this is just a text box! I thought we weren't using TextBoxes? ...

uCan Post WordPress Plugin Demo - Cartpauj & iComNow
This is a demo for the uCan Post WordPress plugin by cartpauj. This plugin lets users create posts and site content without having to access ...

Jennifer Semtner [ Web Designer / Developer ] » CSS
If you're using Grails and the Grails UI plugin's autocomplete feature, you may have noticed all of your textboxes have disappeared in Chrome ...

Resources last updated: 11/24/2015 1:33:21 PM