最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set values for all form elements from an object - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 5
Object.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/

发布评论

评论列表(0)

  1. 暂无评论