This blog will seem simple to most but if it helps one person then mission accomplished!

As a programmer I often fall into bad habits. Mostly to speed up my job as I have old code that I will just re-use even if it may not be the best way to accomplish the task.

I've gotten pretty reliant on CFForm and more so "Binding" between form fields. A part of this I find myself doing a lot is related to screens I write for users to edit data. So the first form field will be a select box, then once selected I fill the rest of the form fields in. So binding makes this pretty easy with the built in AJAX that ColdFusion has built in. But why not just roll my own JavaScript? before ColdFusion included the handy bindings I would do silly things like have a bunch of value pairs in the class attribute or some other open attribute. Then with JavaScript I would parse through that string and pick out what I wanted/needed.

DUMB! Works, yet so much code to accomplish such a simple tasks.

data-


Somewhere along the way I started to use data-attributes in my forms. This simple switch in technique has made my code so much cleaner and very easy to de-bug or make changes in needed. I also feel better about not "cheating" and using the built in CFajax.

So lets look at a simple example: 

Here's an example select box with data attributes: 
<select name="AddressID" id="AddressID" onChange="SetFormFields();">
<option value="">[Select Address to Edit]</option>
    <cfoutput query="GetLocs">
    <option value="#AddressID#"  data-Address="#Address#" data-City="#City#" data-State="#State#" data-Zip="#Zip#">#Address# #City#, #state#  #zip#</option>
    </cfoutput>
</select>
Very simple, and very clean. 

Now the JavaScript to use these data attributes:
<script>
     function SetFormFields() {

    var mySelect = document.getElementById(''AddressID');

    document.getElementById('Address').value = mySelect.options[mySelect.selectedIndex].attributes['data-Address'].value;
    document.getElementById('City').value = mySelect.options[mySelect.selectedIndex].attributes['data-City'].value;
    document.getElementById('State').value = mySelect.options[mySelect.selectedIndex].attributes['data-State'].value;
    document.getElementById('Zip').value = mySelect.options[mySelect.selectedIndex].attributes['data-Zip'].value;

    }
</script>
And that's it. A simple and clean way to populate many fields with a single select box using JavaScript and data-Attributes!



Leave a Reply.