WillSquire
2/19/2016 - 12:17 PM

valSync - A small jQuery extension library which adds the $.valSync function to keep the values of the selected DOM elements synchronised wh

valSync - A small jQuery extension library which adds the $.valSync function to keep the values of the selected DOM elements synchronised when changed.

/**
 * valSync
 * =======
 * A small jQuery extension library which adds the $.valSync function to keep
 * the values of the selected DOM elements synchronised when changed.
 *
 * @author Will Squire <will_squire@hotmail.co.uk>
 *
 * Usage
 * -----
 * To only sync the values on change, use:
 * $('.some-selector').valSync();
 *
 * To sync the values on change and set the initial value for all:
 * $('.some-selector').valSync('initial value');
 */
jQuery.fn.extend({
  valSync: function(value) {
    "use strict";
    var fields = this;
    // Sets all elements to given value except for the ignored element
    function setVals(value, ignore_element) {
      fields.each(function(index, element) {
        if (element !== ignore_element) {
          $(element).val(value);
        }
      });
    }
    // Add an event listener to each of the fields to keep in sync
    fields.each(function(index, element) {
      if (typeof value !== 'undefined') {
        $(element).val(value);
      }
      $(element).change(function() {
        setVals($(this).val(), this);
      });
    });
  }
});