Skip to content

Instantly share code, notes, and snippets.

@maxlawton
Last active August 29, 2015 14:16
Show Gist options
  • Save maxlawton/664f6ed04eb6ad732845 to your computer and use it in GitHub Desktop.
Save maxlawton/664f6ed04eb6ad732845 to your computer and use it in GitHub Desktop.
Populate form inputs with content from elements with matching 'itemprop' attributes.

jQuery.populateDataProps()

Find inputs with a [data-value-prop] attribute and set their value to the 'content' attribute of an children of $source whose [itemprop] matches the input's [data-value-prop].

Example

HTML
 <div id="item" itemscope>
   <data itemprop="foo" content="1234">One, and a two-three-four!</data>
   <meta itemprop="bar" content="raise the bar"/>
 </div>
 <form id="inputs">
   <input name="item[foo]" type="text" data-value-prop="foo"/>
   <input name="item[bar]" type="hidden" data-value-prop="bar"/>
 </form>
JavaScript
 $( '#inputs' ).populateDataProps( $( '#item' ) );

Afterwards, the form will have the following data:

{ "item": { "foo": 1234, "bar": "raise the bar" } }
/**
* jQuery.populateDataProps()
* ==========================
*
* Find inputs with a [data-value-prop] attribute and set their value
* to the 'content' attribute of an children of $source whose
* [itemprop] matches the input's [data-value-prop].
*
* Example
* -------
*
* ```html
* <div id="item" itemscope>
* <data itemprop="foo" content="1234">One, and a two-three-four!</data>
* <meta itemprop="bar" content="raise the bar"/>
* </div>
* <form id="inputs">
* <input name="item[foo]" type="text" data-value-prop="foo"/>
* <input name="item[bar]" type="hidden" data-value-prop="bar"/>
* </form>
* ```
*
* ```js
* $( '#inputs' ).populateDataProps( $( '#item' ) );
* ```
*
* Afterwards, the form will have the following data:
*
* ```json
* { "item": { "foo": 1234, "bar": "raise the bar" } }
* ```
*/
(function ( $ ) {
$.fn.populateDataProps = function ( $source ) {
var _bindValueFromSource = function ( ) {
var $this = $( this ),
prop = $this.data( 'valueProp' ),
$sourceItem = $source.find( '[itemprop="' + prop + '"]' );
if ( $this.is( 'input' ) && $sourceItem.length ) {
$( this ).val( $sourceItem.first().attr( 'content' ) );
}
};
return this.each(function () {
$( this ).find( '[data-value-prop]' ).each( _bindValueFromSource );
});
};
})( window.jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment