微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript 将数据插入表单的输入 - 用数据填充表单

如何解决Javascript 将数据插入表单的输入 - 用数据填充表单

什么是最快的 - 在 javascript 中填充表单的“性能”方式。

我有这个并且它可以工作,但我在想有没有更好或更快的方法来做到这一点?

async function PopulateUpdateForm(formID)
{
    var currentForm = document.getElementById(formID);  // Get the form   
    var resPrommise = await GetUserData();  // Get responce
 

     // Populate the Form
     await resPrommise.json().then(content => // Get the response content
    {
         if (content != null)
         {  
             currentForm['email'].value = content['email'];
             currentForm['firstname'].value = content['firstname'];
             currentForm['lastname'].value = content['lastname'];
             if (content['age'] != 0)
             {
               currentForm['age'].value = content['age'];
             }
             currentForm['phonenumber'].value = content['phonenumber']; 
         }
    
    });
}

解决方法

async function PopulateUpdateForm(formID)
{
    var currentForm = document.getElementById(formID);  // Get the form   
    var resPrommise = await GetUserData();  // Get responce
 

     // Populate the Form
     await resPrommise.json().then(content => // Get the response content
    {
         if (content == null) return;
         ['email','firstname','lastname','phonenumber'].forEeach(x => 
          currentForm[x].value = content[x];
         )
         if (content['age'] != 0) currentForm['age'].value = content['age'];
  
    });
}

,

为了可读性,我会保留您填充表单的方式,除非您使用 React 或 Vue 等响应式框架。

,

有更好的方法来做到这一点。您不必手动设置值,而是可以动态设置...

使用这个:

function PopulateUpdateForm(currentForm,data) {   
$.each(data,function(key,value) {
// Populate Form data by input Name
    var ctrl = $('[name='+key+']',currentForm);  
    switch(ctrl.prop("type")) { 
        case "radio": case "checkbox":   
            ctrl.each(function() {
                if($(this).attr('value') == value) $(this).attr("checked",value);
            });   
            break;  
        default:
            ctrl.val(value); 
    }  
});  

}

并通过调用使用它

var currentForm = document.getElementById(formID);  // Get the form   
var data = GetUserData();  // Get responce data
PopulateUpdateForm(currentForm,data)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。