Skip to content

Instantly share code, notes, and snippets.

@olimortimer
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olimortimer/3c675a367b3e3e9f0103 to your computer and use it in GitHub Desktop.
Save olimortimer/3c675a367b3e3e9f0103 to your computer and use it in GitHub Desktop.
JS: Pre-populate Fields
// Populate our field
function populateField($container, name, value) {
var $field = $container.find('[name="'+name+'"]');
// Skip if our field doesn't exist
if($field.length == 0) return false;
if($field.is(':radio')) {
$field.filter('[value="'+value+'"]').prop('checked', true);
// Toggle our button state, if we're using a btn-group
$field.filter('[value="'+value+'"]').parent('label.btn').button('toggle');
} else if($field.is('select')) {
$field.find('option[value="'+value+'"]').attr('selected', true);
// If select2, refresh it
if($field.hasClass('select2')) $field.select2();
} else {
$field.val(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment