Last active
August 29, 2015 13:57
-
-
Save blpraveen/9778372 to your computer and use it in GitHub Desktop.
Populate field from json Object
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
$.fn.populate = function populate(value,key) { | |
var input_fields= $(this),new_value=value; | |
patterns = { | |
key: /[a-z0-9_-]+|(?=\[\])/gi, | |
push: /^$/, | |
} | |
input_fields.each(function(i,input_field) { | |
var val,key = $(input_field).attr('name'); | |
if(new_value instanceof Array) { | |
val= new_value[i]; | |
} | |
if(new_value instanceof Object) { | |
var keys = key.match(patterns.key), k; | |
if (patterns.push.test(keys[(keys.length - 1)])) { | |
new_key = key.replace(/\[\]$/, ''); | |
} else { | |
new_key = key; | |
} | |
var prevObj; | |
var count = keys.length; | |
$(keys).each(function(i,val) { | |
if(i == 0) { | |
if(value[val] === undefined){ | |
new_value[new_key] = ""; | |
return false | |
} | |
prevObj = value[val]; | |
} else if (patterns.push.test(val)) { | |
new_value[new_key] = prevObj; | |
} else { | |
prevObj = prevObj[val]; | |
} | |
if(i == (count -1)) { | |
new_value[new_key] = prevObj; | |
} | |
}); | |
val= new_value[new_key]; | |
} | |
if ($(input_field).is('select')){ | |
$('option', $(input_field)).each(function() { | |
if (this.value == val) | |
this.selected = true; | |
}); | |
} else if ($(input_field).is('textarea')) { | |
$(input_field).val(val); | |
} else { | |
switch($(input_field).attr("type")) { | |
case 'radio': | |
// use the single value to check the radio button | |
$(input_field).checked = ($(input_field).val() != '' && val.toString() == $(input_field).val()); | |
break; | |
case "text": | |
case "hidden": | |
val = val == null ? '' : val; | |
$(input_field).val(val); | |
break; | |
case "checkbox": | |
var new_values = new_value.constructor == Array ? new_value : [new_value]; | |
for(var j = 0; j < new_values.length; j++) { | |
$(input_field).checked |= $(input_field).val() == values[j]; | |
} | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment