February 23, 2017 Design development javascript jquery 0

This is definitely the most simple and one of the most effective 2 way data binding method with jQuery. Just simply add the custom attribute bind to any element, and it will bind the data to all elements with the same bind value. See the code below get the idea:

One:

This div’s content
will be replaced when you edit the input below


Two:

This div’s content
will be replaced when you edit the input below


You can add as many “models” as you want in your HTML, as the data will bind to any and every element that has the same bind attribute value. Even though this is not the most advance data binding technique, I’m pretty sure its simplicity and usefulness can help in many situations. Please note, than any change in the div’s html content will also be reflected in the input values – open your developers tool/console, manually modify the content of the div, and you’ll see how the input values with the same bind attribute value will change as well.

Here is the HTML:

1
2
3
4
<div style="border: 1px solid pink; padding: 10px;" bind="any_name">This div's content
will be replaced when you edit the input below</div>
<input type="text" placeholder="First input with same bind value" bind="any_name"/>
<input type="text" placeholder="Second input with same bind value" bind="any_name"/>

 

And here is the Javascript code:

1
2
3
4
5
6
7
8
9
10
11
12
<script>
$("*[bind]").on('change keyup', function (e) {
 var to_bind = $(this).attr('bind');
 $("*[bind='"+to_bind+"']").html($(this).val());
 $("*[bind='"+to_bind+"']").val($(this).val());
})
$("div[bind]").bind("DOMSubtreeModified",function(){
 var to_bind = $(this).attr('bind');
 $("*[bind='"+to_bind+"']").html($(this).html());
 $("*[bind='"+to_bind+"']").val($(this).html());
});
</script>

Obviously, you need to include jQuery in order for this to work. Happy data binding!