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:
$("#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>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
The code for my solution basically comes down to 3 parts:
- 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.
- Quickly turn the form into data I can send over the wire using serialize().
- 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 ;)
Archived Comments
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).
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.
yeah, that's odd. i can swear i tested it before i commented. shrug... as you were. :)
This code doesn't work for me. Am I missing something?
How doesn't it work? It's super simple jQuery. What browser are you using?
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.
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.
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. :)
Got it to work. I was missing the test2.cfm file. Works fine now.
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 ...
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.
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.
Okay ... well that explains that ... my misunderstanding ....
Nice demo, Ray. thanks very much.
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
:)
onPropertyChange only handles when actual properties of the html element are changed, no? I don't think that's necessary for this example.
I just tested in IE9 and it worked fine as is.
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(){......
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);
?>
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?
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.
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.
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.
I'm sorry, but what do you mean by "run this example"? You can run the demo by hitting the link above.
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
The data is sent via a URL parameters. All I did was
<cfdump var="#url#">
many thanks!
For some reasons, jquery load() .cfm is not working for me. Any idea? We are using IE 8. Thank you.
How is it not working?
It's not loading the .cfm file (nothing happen when value changed). I have no problem to load .txt file.
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.
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.
I'm confused. So it works ok in Firefox, but not IE? Oh - because the console.log messages break it. Just remove them.
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.
So to be clear: It works perfectly in Firefox. It does not in IE - and you removed the console.log messages. Right?
It works perfectly in Firefox. It does not in IE. And I have removed console messages. Thank you.
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.
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.
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.
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.
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!!!
Woot! Glad you got it!
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!
Just add this:
$("#mainForm").trigger("change");
After you've defined the change handler that is.
Works like a charm. Thanks!
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?
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...
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.