2-way binding (jQuery)

by Alon Rotem

HTML

<h1>Typical JQuery implementation:</h1>
<div>
  Enter your name: <input type="text" id="txtName"/>
  Hello, <span id="mirror"></span>!
  <div>
    <input type="button" id="btnUpdatetext" value="Update text"/>
  </div>
</div>
<h2>Form validation:</h2>
<ul>
<li>No built-in validation</li>
<li>Use an plugin library like <a href="https://jqueryvalidation.org/" target="top">jQuery Validation Plugin</a></li>
</ul>
<br/><br/>
See <a href="https://jsfiddle.net/alrotem/j0rukygt/" target="top">AngularJS implementation</a>

CSS

body {
    font-family: arial;
    font-size: 12px;
}
* {
    margin-top: 5px;
    margin-bottom: 5px;
}

JavaScript

$(function() {
	//Lame fake data binding
  
  //text in the textbox changed: update the span
  $("#txtName").keyup(
  	function(event){
  		$("#mirror").text($(this).val()); 
    });

	//text in the span changed: update the textbox
	$("#mirror").on("DOMSubtreeModified",
  	function(event){
    	$("#txtName").val($(this).text());
    }
  );
  
  //button clicked: update the span text
  $("#btnUpdatetext").click(
  	function(event){
    	$("#mirror").text("Alon");
    });
    
  //data model? none.
});