I have a form in html and I need to set the values for all the elements in the form .
I have an object like this containing all the names of fields and thier values :-
obj= {
name:'john',
age:10,
Country:'USA'
}
Instead of accessing each element of the form and setting the values , Is there any way to set the values directly using jquery or something without much code ?
Whats the easiest way to do this ?
I have a form in html and I need to set the values for all the elements in the form .
I have an object like this containing all the names of fields and thier values :-
obj= {
name:'john',
age:10,
Country:'USA'
}
Instead of accessing each element of the form and setting the values , Is there any way to set the values directly using jquery or something without much code ?
Whats the easiest way to do this ?
Share Improve this question edited Jan 5, 2018 at 12:15 Ganesh Rana 639 bronze badges asked Jan 5, 2018 at 12:12 Natesh bhatNatesh bhat 13.4k13 gold badges93 silver badges134 bronze badges 1- Yes, loop over the keys of the object and match them to the names of the elements. Then you can just set their values. If you want more specific help on exactly how to do that, show us what you've attempted so far. – Rory McCrossan Commented Jan 5, 2018 at 12:13
3 Answers
Reset to default 5Object.keys(obj).forEach(key => {
$(`input[name="${key}"]`).val(obj[key]);
})
This loops through each object property, findes the input with the same name as the object property key, and sets its value to the property value
https://jsfiddle/53kjnunj/
Here is the code for setting data from object to form elements
function loadFormElements(form, data ) {
$.each(data, function(index, value) {
var element = $(form).find("input[name='" + index + "']");
if( $(element).is(":checkbox") ) {
if( value == "Y" ) {
$(element).prop('checked',value == "Y" );
} else {
$(element).removeProp('checked' );
}
} else {
element.val(value);
}
});
}
Call the above method as below
loadFormElements( $("#myform"),obj);
You can do it without jQuery like this:
<form>
<input type="text" id="name">
<input type="text" id="age">
<input type="text" id="country">
</form>
JS:
obj= {
name:'john',
age:10,
Country:'USA'
}
document.getElementById('name').value = obj.name;
document.getElementById('age').value = obj.age;
document.getElementById('country').value = obj.Country;
https://jsfiddle/292bcxux/