简体   繁体   English

使用jQuery从关联数组填充表单

[英]Populate a form with data from an associative array with jQuery

Last time I asked about the reverse process , and got some very efficient answers. 上次我询问了相反的过程 ,得到了一些非常有效的答案。 I'm aiming for least lines of code here. 我的目标是最少的代码行。 I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it. 我有{fieldname:data}格式的字段和关联数组,我想用它填充相应的表单。

如果表单元素的ID设置为fieldname:

$.each(myAssocArry, function(i,val) { $('#'+i).val(val); });

When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of: 当我为一个项目做这个时,我发现设置选择字段,单选按钮和复选框的值需要更复杂的代码,类似于:


jQuery.each(data, function (name,value) {
  jQuery("input[name='"+name+"'],select[name='"+name+"']").each(function() {
    switch (this.nodeName.toLowerCase()) {
        case "input":
            switch (this.type) {
                case "radio":
                case "checkbox":
                    if (this.value==value) { jQuery(this).click(); }
                    break;
                default:
                    jQuery(this).val(value);
                    break;
            }
            break;
        case "select":
            jQuery("option",this).each(function(){
                if (this.value==value) { this.selected=true; }
            });
            break;
    }
  });
});

I haven't tested this code so I hope there are no silly syntax errors that I should have caught. 我没有测试过这段代码,所以我希望没有愚蠢的语法错误,我应该抓住它。 Hope this helps. 希望这可以帮助。

I am not allowed to comment on the comments here (yet), so .... As noted in the comment, the jQuery .val(val) method handles setting radio buttons,checkboxes and selects. 我不允许在这里评论这些评论,所以....正如评论中所指出的,jQuery .val(val)方法处理设置单选按钮,复选框和选择。

You will still need to put select[name=...] into your jQuery selector pattern or the select elements won't be updated. 您仍然需要将select [name = ...]放入jQuery选择器模式中,否则select元素将不会更新。

Or similar to the previous suggestion using the field names instead of ids: 或者类似于之前使用字段名称而不是ID的建议:

$.each(data, function(name,value) {
    $("input[name='" + name + "']").val(value);
});

I have not seen jQuery handle passing a single (non-array) value into val() for a radio or checkbox input. 我还没有看到jQuery句柄将单个(非数组)值传递给val()以用于收音机或复选框输入。 You have to be sure to wrap the single value into an array. 您必须确保将单个值包装到数组中。

I have also typically not wanted to alter the values of button-ish inputs, so I filter those out. 我通常也不想改变button-ish输入的值,所以我把它们过滤掉了。

Here's a function that handles the array wrapping, button filtering, and also restricts the input selection to a given form element. 这是一个处理数组包装,按钮过滤的函数,并且还将输入选择限制为给定的表单元素。 The form parameter is optional. 表单参数是可选的。 If left off/null/undefined, then all inputs on the page will be selected. 如果不使用/ null / undefined,则将选择页面上的所有输入。

function populateForm(data, form) {
    $.each( data, function(name, value) {
        var input = $(":input[name='" + name + "']:not(:button,:reset,:submit,:image)", form );
        input.val( ( !$.isArray( value ) && ( input.is(':checkbox') || input.is(':radio') ) ) ? [ value ] : value );
    } );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM