Hello,
I have a dropdown box (course name) and a text field (course fee).
When a user selects a course in the dropdown, the fee for that
course (which is in the database) should get populated in the
text field. How do we go about implementing this? I am using
Coldfusion and Javascript.
Thanks in advance,
jnag
There are two options depending on the size of the dataset you are
using. You could use ColdFusion to populate a JavaScript associative
array with the fees, or you write a web service that returns the fees
and use XmlHttpRequest to interact with it.
If you have a lot of fee data, the size of the HTML+JavaScript
returned by the web server will be large and therefore take a while to
load. You could do something like this:
<script type="text/javascript>
var fees = {};
<!--- Populate fees --->
<cfloop query="fees">
fees["#fees.course_id#"] = #fees.fee_amount#;
</cfloop>
// Listen for changes to the select box
document.getElementById('course_chooser').onchange = function() {
document.getElementById('fee_textbox').value =
fees[this.options[this.selectedIndex].value];
}
</script>
But remember, if you have a lot of courses, this little snippet of
code can turn into a very large page. But, after the page is loaded
the fees will appear instantaneously when you change the select box.
The way I would do it would be to create a script that returns the
fees given the course number:
get_fees.cfm?course_id=CMPUT401
Now you use the XmlHttpRequest object to perform an AJAX request to
get the fees. I'm not going to get into the details of doing an AJAX
request (there's plenty of documentation lying around), but it would
look something like this:
<script type="text/javascript">
// Listen for changes to the select box
document.getElementById('course_chooser').onchange = function() {
document.getElementById('fee_textbox').value =
doAjax("get_fees.cfm?course_id=" +
this.options[this.selectedIndex].value);
}
</script>
This method will give you a very fast initial page load, but there
will be a short delay in displaying the fees.