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 ;)