Last active
August 29, 2015 13:59
-
-
Save mbaez/10478264 to your computer and use it in GitHub Desktop.
Set and get data using html data-attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<header> | |
<label> Hi <span data-attr="fullname">?</span>! | |
</header> | |
<form id="from-data"> | |
<fieldset> | |
<label class="control-label" for="input-username">Username</label> | |
<input data-attr="username" type="text" id="input-username" > | |
<label class="control-label" for="input-name">full name</label> | |
<input data-attr="fullname" type="text" id="input-full-name" > | |
<label class="control-label" for="input-email">Email</label> | |
<input data-attr="email" type="text" id="input-email" > | |
<label class="control-label" for="input-address">Address</label> | |
<input data-attr="address" type="text" id="input-address" > | |
</fieldset> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getAttributes (target) { | |
//se define el target, el target o scope es todo el contenedor del view. | |
//se conigura el collapse | |
var data = {}; | |
$(target).find('[data-attr]').each(function (e) { | |
var attr = $(this).attr('data-attr'); | |
var value = $(this).val(); | |
if (value.length > 0 ) { | |
data[attr] = value; | |
} | |
}); | |
/*se setean los valores*/ | |
return data; | |
}; | |
function setAttributes (target, data) { | |
var attrName = ""; | |
if (options == null) { | |
return; | |
} | |
//se define el target, el target o scope es todo el contenedor del view. | |
var $target = $(target); | |
//se conigura el collapse | |
for (var attr in data) { | |
var value = data[attr]; | |
var targetDom = $target.find("[data-attr='" + attr + "']"); | |
value = value == null ? "" : value; | |
if ($(targetDom).is("input") || $(targetDom).is("select")) { | |
$(targetDom).val(value); | |
} else { | |
$(targetDom).text(value); | |
} | |
} | |
}; | |
//how to use | |
var data ={ | |
username :"mbaez", | |
fullname :"Maximiliano Báez", | |
email: "[email protected]", | |
addres : "street 1 " | |
} | |
//set all data | |
setAttributes ($("header, #form-data"), data ); | |
newData = getAttributes ($("#form-data")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment