Skip to content

Instantly share code, notes, and snippets.

@Swimburger
Last active December 22, 2016 15:02
Show Gist options
  • Save Swimburger/efa304f1206fe287b04d2cff3b181b5d to your computer and use it in GitHub Desktop.
Save Swimburger/efa304f1206fe287b04d2cff3b181b5d to your computer and use it in GitHub Desktop.
Keep multiple fields their value in sync using jquery (two way binding), see https://jsbin.com/zicocop/edit?html,js,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Two way binding</title>
</head>
<body>
<h1>Two way sync</h1>
<select id="month1">
<option value="">Please select a moth</option>
<option value="jan">January</option>
<option value="feb">February</option>
<option value="mar">March</option>
</select>
<select id="month2">
<option value="">Please select a moth</option>
<option value="jan">1</option>
<option value="feb">2</option>
<option value="mar">3</option>
</select>
<select id="month3">
<option value="">Please select a moth</option>
<option value="jan">Jan</option>
<option value="feb">Feb</option>
<option value="mar">Mar</option>
</select>
<br>
<input type="text" id="text1">
<input type="text" id="text2">
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
$.fn.keepInSync = function($targets) {
// join together all the elements you want to keep in sync
var $els = $targets.add(this);
$els.on("keyup change", function() {
var $this = $(this);
// exclude the current element since it already has the value
$els.not($this).val($this.val());
});
return this;
};
//use it like this
$("#month1").keepInSync($("#month2, #month3"));
$("#text1").keepInSync($("#text2"));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment