jQuery Quickie: On form change update a div

This post is more than 2 years old.

This question came to me on Saturday and I was pretty surprised by how quick it was to solve. I say that even being an already huge believer in the thinking that jQuery can basically out trump Unicorns for pure magic and awesomeness. Basically the issue was this. The reader had a set of form fields (text boxes, checkboxes, drop downs, etc), and if any of them changed, she wanted to update a div that was driven by the current values of the form. If you get rid of the console.log messages I used in my example, the code takes a grand total of three lines. Here's what I built:

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() {

$("#mainForm").change(function() {
	console.log("changed...");
	var data = $(this).serialize();
	console.log(data);
	$("#results").load("test2.cfm?"+data);		
})

}) </script> </head>

<body>

<form id="mainForm"> name: <input type="text" name="name" /><br/> age: <input type="text" name="age" /><br/> gender: <select name="gender"> <option value="m">Male</option> <option value="f">Female</option> </select><br/> foo: <input type="radio" name="foo" value="1">One<br/> <input type="radio" name="foo" value="2">Two<br/> <input type="radio" name="foo" value="3">Three<br/> goo: <input type="checkbox" name="goo" value="1">One<br/> <input type="checkbox" name="goo" value="2">Two<br/> <input type="checkbox" name="goo" value="3">Three<br/> <p> <input type="submit"> </form>

<div id="results"> </div>

</body> </html>

The code for my solution basically comes down to 3 parts:

  1. Listen for form changes by simply binding to the form and the change event. jQuery will listen in to all the fields inside the form.
  2. Quickly turn the form into data I can send over the wire using serialize().
  3. Tell jQuery to do a quick GET on the URL and load the results into my div.

And that's it. My test2.cfm file just echos back the URL scope, but obviously would need to actually do something with those values. If you want to try this yourself, just hit the big demo button below. And yes - I removed the console.log messages. grumble ;)

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by todd sharp posted on 5/23/2011 at 9:42 PM

Might want to do it on blur() instead since changing the dropdown (for example) with a keypress doesn't fire the change event (even when you tab off).

Comment 2 by Raymond Camden posted on 5/23/2011 at 9:48 PM

It worked when I clicked the drop down and used the down arrow. When I hit up to go back to male, it didn't get it till I clicked outside, which seems like it would be fair.

Comment 3 by todd sharp posted on 5/23/2011 at 9:53 PM

yeah, that's odd. i can swear i tested it before i commented. shrug... as you were. :)

Comment 4 by Rich Hefter posted on 5/23/2011 at 10:08 PM

This code doesn't work for me. Am I missing something?

Comment 5 by Raymond Camden posted on 5/23/2011 at 10:09 PM

How doesn't it work? It's super simple jQuery. What browser are you using?

Comment 6 by Brian Swartzfager posted on 5/23/2011 at 11:36 PM

A while back, I had a need to highlight any changes a user made on a form. Ended up writing a jQuery plugin to handle it called dirtyFields. I recently put up the code (and a link to a website with documentation and working examples) on GitHub: https://github.com/bcswartz...

Might be overkill for your reader's situation, but thought I'd mention it.

Comment 7 by daddy-o posted on 5/23/2011 at 11:53 PM

Grumbing about console.log... Because this causes errors on browsers that aren't using the console, do this:

if(console.log){console.log("changed...");};

Then it works if it can, and is ignored if it can't.

Comment 8 by Raymond Camden posted on 5/23/2011 at 11:55 PM

daddy-o: I know, I know. It's an old "issue" on this blog. I post a demo. People say it doesn't work. It's the console.

Frankly, any developer not using a console-enabled browser is bringing a knife to a gun fight. It's just plain wrong.

That being said, I _have_ been trying to remove them for demos lately. :)

Comment 9 by Rich Hefter posted on 5/24/2011 at 12:02 AM

Got it to work. I was missing the test2.cfm file. Works fine now.

Comment 10 by Edward - Florida SEO posted on 5/24/2011 at 2:26 AM

As Todd mentioned, I can't seem to get the change to work for the text field ... maybe need to set a default text value to empty to test for equality ...

Comment 11 by Raymond Camden posted on 5/24/2011 at 2:30 AM

Ah so do you want it to change _as_ you type? To me, I read the original request (which I don't have on the blog entry) as being ok with 'on tab out'. Obviously we can change (easily) how often things change.

Comment 12 by Jaana Gilbert posted on 5/24/2011 at 3:44 AM

I'm the mysterious *she* :) .
Raymond was kind enough to help me out really quickly on Saturday and I was able to move along with my project.
This is part of admin controls where event coordinator matches members up for different club activities.

For text field, it would be triggered once tabbing out or moving on to a different field, not as-you-type.

Earlier today I had another question for Raymond about I needed the newly created div content be able to trigger a 3rd div. His quick response was to Google for jQuery and delegate and that got me moving along again and I got my second problem fixed :)

Raymond is super fast and I really appreciate his help.

Comment 13 by Edward - Florida SEO posted on 5/24/2011 at 4:21 AM

Okay ... well that explains that ... my misunderstanding ....

Comment 14 by SuperAlly posted on 5/24/2011 at 7:01 AM

Nice demo, Ray. thanks very much.

Comment 15 by Misty posted on 5/24/2011 at 6:06 PM

Just a Note, I went far and checked on IE, there is an Event OnPropertyChange() which works only in IE so this will work if needs IE Specific

$(document).ready(function() {

$("#mainForm").bind('propertychange',function() {
console.log("changed...");
var data = $(this).serialize();
console.log(data);
$("#results").load("test2.cfm?"+data);
})
})
or if we wanna use it dor Mozilaa we can use the event:

DOMAttrModified in stead of PropertyChange

:)

Comment 16 by todd sharp posted on 5/24/2011 at 6:33 PM

onPropertyChange only handles when actual properties of the html element are changed, no? I don't think that's necessary for this example.

Comment 17 by Raymond Camden posted on 5/24/2011 at 6:50 PM

I just tested in IE9 and it worked fine as is.

Comment 18 by Misty posted on 5/24/2011 at 6:57 PM

Yup! Its not necessary but provided as a example that by using tbind attribute we can use multile events like

.bind('keyup change keydown keypress',function(){......

Comment 19 by Simon posted on 6/11/2011 at 6:52 PM

was struggling to use this with PHP, after an hour so or so.
Here are is a working version for anyone else needing the same

////////HTML & Jquery //////////////
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/..."></script>
<script>
$(document).ready(function() {

$("#mainForm").change(function() {
console.log("changed...");
var data = $(this).serialize();
console.log(data);
$("#results").load("test_results.php?data="+data);
})
})
</script>
</head>

<body>

<form id="mainForm">
name: <input type="text" name="name" /><br/>
age: <input type="text" name="age" /><br/>
gender:
<select name="gender">
<option value="m">Male</option>
<option value="f">Female</option>
</select><br/>
foo: <input type="radio" name="foo" value="1">One<br/>
<input type="radio" name="foo" value="2">Two<br/>
<input type="radio" name="foo" value="3">Three<br/>
goo: <input type="checkbox" name="goo" value="1">One<br/>
<input type="checkbox" name="goo" value="2">Two<br/>
<input type="checkbox" name="goo" value="3">Three<br/>
<p>
<input type="submit">
</form>

<div id="results">
</div>

</body>
</html>
////////////PHP/////////
<?
print_r($_GET);
?>

Comment 20 by Raymond Camden posted on 6/11/2011 at 6:59 PM

In the future, please use pastebin.

Curious - what did you struggle with? The PHP just echos out the stuff so what was difficult about it?

Comment 21 by Earl Nall posted on 8/9/2011 at 5:17 PM

Long time CF developer and new to jQuery - so please bear with me. I am missing something simple her and I can't seem to make a connection. How do I take the results from test2.cfm and put into a database, or even redirect to test2.cfm so more processing can be done on the form results)? I see the form results in the URL when the submit button is pressed and it looks like test2.cfm has a CFDUMP. I assume there is something simple I don't understand - but obviously I am missing something on how to get from results from jquery sent to a .cfm file for processing.

Comment 22 by Raymond Camden posted on 8/9/2011 at 6:47 PM

test2.cfm is simply there to show stuff. It should not be used to save to the db. Rather, you want the regular form submission to handle that. My form has no action tag, which means it will post to itself. Therefore, I'd add code that looks for the form submission (isDefined("form.name") is one way) and do the db insert there.

Comment 23 by Alex posted on 3/1/2012 at 2:15 PM

Hi, my name is alessandro from italy and i write, I'm studying Coldfusion recently and i read this site to try to learn something. I can not find a solution to run this example. I would be grateful if someone could help me. Thanks and sorry for my bad English.

Comment 24 by Raymond Camden posted on 3/1/2012 at 4:54 PM

I'm sorry, but what do you mean by "run this example"? You can run the demo by hitting the link above.

Comment 25 by Alex posted on 3/1/2012 at 7:18 PM

Hi, my English is probably more bad than I thought :-) I meant that the test does not work locally. I can not figure out which variable to pass the file to run the test2.cfm cfdump! They are the beginning of the study of coldfusion, but running the cfdump of form.mainForm not get any results. thanks

Comment 26 by Raymond Camden posted on 3/1/2012 at 7:47 PM

The data is sent via a URL parameters. All I did was

<cfdump var="#url#">

Comment 27 by Alex posted on 3/2/2012 at 10:33 PM

many thanks!

Comment 28 by Anita posted on 6/13/2012 at 1:22 AM

For some reasons, jquery load() .cfm is not working for me. Any idea? We are using IE 8. Thank you.

Comment 29 by Raymond Camden posted on 6/13/2012 at 1:27 AM

How is it not working?

Comment 30 by Anita posted on 6/13/2012 at 1:53 AM

It's not loading the .cfm file (nothing happen when value changed). I have no problem to load .txt file.

Comment 31 by Raymond Camden posted on 6/13/2012 at 1:56 AM

So - are you saying everything but the load runs? So you see the console.log? If so - check the XHR portion of your Chrome Dev Tools and see what's happened with the network request.

Comment 32 by Anita posted on 6/13/2012 at 2:17 AM

I try to use Firefox and everything runs (including console.log) but with IE 8, I can only see the logs. It's not even showing the XHR portion.

Comment 33 by Raymond Camden posted on 6/13/2012 at 2:21 AM

I'm confused. So it works ok in Firefox, but not IE? Oh - because the console.log messages break it. Just remove them.

Comment 34 by Anita posted on 6/13/2012 at 2:37 AM

Sorry to confuse you but "console.log" is not the issue. The problem is test2.cfm does not even load to the page. There is no error message either. NOTE: I have no problem using your demo page.(both IE and Firefox) Thank you so much for being so patient with me.

Comment 35 by Raymond Camden posted on 6/13/2012 at 2:40 AM

So to be clear: It works perfectly in Firefox. It does not in IE - and you removed the console.log messages. Right?

Comment 36 by Anita posted on 6/13/2012 at 2:47 AM

It works perfectly in Firefox. It does not in IE. And I have removed console messages. Thank you.

Comment 37 by Raymond Camden posted on 6/13/2012 at 2:51 AM

So IE is notorious for caching issues. Try changing

$("#results").load("test2.cfm?"+data);

to

$("#results").load("test2.cfm?x="+(new Date()) + data);

Basically - I added a random-ish value to the end.

Comment 38 by Anita posted on 6/13/2012 at 3:07 AM

Still no luck. This time it does not even work in Firefox. Firebug shows "Error: Syntax error, unrecognized expression: (Central Daylight Time)name=test&age=&gender=m...".
I changed it to
$("#results").load("test2.cfm?x="+Math.random() + data);

Then it works in Firefox but still not in IE.

Comment 39 by Anita posted on 6/13/2012 at 3:11 AM

The interesting thing is I do not have problem with your demo page in IE so it got to be something I didn't do or shouldn't have done.

Comment 40 by Raymond Camden posted on 6/13/2012 at 5:07 AM

Ah, I didn't actually test it - I just typed it in - so that was a mistake. Math.random() was a smart change.

So as to why it fails in IE just on your server, at this point I don't know. Since IE8 doesn't have a tool like Firebug or Chrome Dev Tools, you could consider Charles or Service Capture.

Comment 41 by Anita posted on 6/13/2012 at 11:03 PM

Found the problem. I setup the "jquery.min.js" file on our server instead of going through the firewall and that fixed the issue. Thank you for all your help. You are THE BEST!!!

Comment 42 by Raymond Camden posted on 6/14/2012 at 12:08 AM

Woot! Glad you got it!

Comment 43 by Frank posted on 1/27/2013 at 1:38 AM

Is there a way to enter the form with predefined values and have the results displayed in the div when the form is first loaded? I can have checkboxes already checked but I need to make changes in the form before I can see any results displayed.

Thanks!

Comment 44 by Raymond Camden posted on 1/27/2013 at 6:14 PM

Just add this:

$("#mainForm").trigger("change");

After you've defined the change handler that is.

Comment 45 by Frank posted on 1/28/2013 at 12:19 AM

Works like a charm. Thanks!

Comment 46 by Bryn posted on 6/4/2013 at 4:11 AM

Thanks for this post. It hopefully will be a big asset for my Website. I am just having one issue I did not see covered in the comments. When I use the jQuery Autocomplete it does not always recognize the form has changed. I tried change, blur, & focus. I also tried it in Chrome and had the same results. When not using the jQuery Autocomplete it works every time.

Any suggestions?

Comment 47 by Raymond Camden posted on 6/4/2013 at 3:30 PM

If you take the code in my event handler and abstract it out to its own method, something like 'noticeChange', you can then call that from the jQueryUI Autocomplete change event: http://api.jqueryui.com/aut...

Comment 48 by Bryn posted on 6/5/2013 at 12:03 AM

I ended up running the function using the onblur attached to the text fields for the AutoComplete. It is not as elegant as your solution, but it works and my clients won’t know the difference. Thanks again for your blog entry, it helped me discover a great solution for my Website and it is live and working now.