Search code examples
javascriptcompareonbluronfocus

Checking change in form field before executing AJAX store with Javascript OnBlur OnFocus? How?


I am currently executing AJAX query stores on each onblur if this.value is not equal to '', but for users tabbing through a form and not changing anything, this is an insane amount of database query hits for nothing (and yes, I check for changes on the actual database query script, but still).

Here's what I'm doing currently:

<input type="text" name="EUName" id="EUName" value="[whateverdynamicvalue]"
class="contentextformtxt" onblur="if (this.value == '') 
{this.value = '[whateverdynamicvalue]';} else { UpdateEUData();return false; } " />

With the else obviously submitting the form via AJAX.

What I thought about doing was using OnFocus to capture what the content was when the User OnFocuses, and then checking it against this.value OnBlur to see if anything has changed. I'm not sure if I'm on the right track (not very good at javascript) but here's what I have so far.

<input type="text" name="EUAddress1" id="EUAddress1" value=" [whateverdynamicvalue] "
class="contentextformtxtlarge" onblur="if (this.value == '' || this.value == originalfvalue)
{this.value = ' [whateverdynamicvalue] ';} else { UpdateEUData();return false; } " 
onfocus="Var originalfvalue = this.value" />

I'm not sure if that's a best practice or not, but either way, it doesn't work. Any suggestions on how to fix would be awesome! Bottom line, I'm just trying to figure out a way to cut down on the server traffic. I originally was just comparing it to the dynamic value, but the problem is if someone changes the value from value x to value y, and then tries to change it back to value x, obviously comparing it to the dynamic value will not allow it to update because it still thinks the value IS value x, not that it has been changed to value y. Hence why I'm trying to figure out the javascript route.

Any help will be much appreciated in advance! JE


Solution

  • Use the onchange event. It is triggered when the user tabs or clicks out of the field, but unlike onblur it only happens if the value was actually changed.