Two-Way Databinding with jQuery

I was working on a small data entry page and wanted to use jQuery to databind an object to my controls. I was expecting a simple command, like $(“#myControl”).databind(obj.Value), but was surprised to find that one did not exist. The Internet kept telling me to look elsewhere–mostly Knockout–but I was sure that this could be accomplished with jQuery alone.

It turns out that it is easy to do with jQuery, but it’s all manual. I created a function named databind and, for each control, I populate it with the desired property’s value and create an event handler to update the value when the control changes.

function databind() {
    var ctl;

    // a checkbox
    ctl = $("#uxMyCheckbox");
    ctl.attr('checked', model.BoolValue);
    ctl.change(function () { model.BoolValue = this.checked; });

    // a textbox
    ctl = $("#uxMyTextbox");
    ctl.change(function () { model.TextValue = this.value; });

It’s not quite as elegant as I was hoping for, but it’ll do for now. I’ll probably check out Knockout for the future, though.

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “Two-Way Databinding with jQuery”

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: