data binding
by nabeezy
HTML
<input class="input" id="name" type="text" placeholder="Name">
<input class="input" id="address" type="text" placeholder="Address">
<input class="input" id="city" type="text" placeholder="City">
<select name="state" id="state" class="input" >
<option value="none">--</option>
<option value="mn">Minnesota</option>
<option value="wi">Wisconsin</option>
</select>
<input class="input" id="zip" type="text" placeholder="Zip">
<input class="input" id="additional" type="text" placeholder="Optional additional copy">
<p id="label-name"></p>
<p id="label-address"></p>
<p id="label-city"></p>
<p id="label-state"></p>
<p id="label-zip"></p>
<p id="label-additional"></p>
<button id='click'>view console</button>
CSS
input[type=text] {
border: 1px solid #aaaaaa;
border-radius: 3px;
display: block;
margin-bottom: 10px;
padding: 8px;
width: 50%;
}
select {
margin-bottom: 10px;
}
JavaScript
// DEFINE VARIABLES
var dobs = []; // GLOBAL DOBS = data-bound objects array
// DEFINE FUNCTIONS
var performBind = function(){
dobs = []; //THIS CLEARS THE DOBS ARRAY EACH TIME YOU KEYUP
$( ".input" ).each(function( i ) { // this cycles through every "input" element
var newDob = {}; //this instantiates a potential DOB (data-bound object)
newDob.id = this.id; //this adds a property to the object
newDob.c = this.value; //this adds a property to the object
dobs.push(newDob); //this adds the new object to the global array
});
for(k=0;k<dobs.length;k++){ //this cycles through dobs
$('#label-'+ dobs[k].id).text(dobs[k].c); //this uses the global objects id attribute to populate the right fields
}
}
// DEFINE DOM EVENT LISTENERS
$('#click').click(function(){console.dir(dobs);})//this function allows you to view the GLOBAL DOBS object array in console
$('.input').keyup(function(){performBind();}); // this calls the function each time you keyup