【问题标题】:Select checkbox with name[] and values (jquery/javascript)选择带有名称[] 和值的复选框(jquery/javascript)
【发布时间】:2014-09-14 20:18:04
【问题描述】:

我将表单保存为 json 对象,在刷新或重新访问页面时我使用它来重建表单。它工作得很好,除了我在定位名称属性后带有“[]”的复选框时遇到问题。

我的对象:{"product":{"checkboxname":["value1","value2"]}}

// Reset form values from json object
$.each(formStateObjects[presentFormElementID], function(name, val){

    var $el = $('[name="'+name+'"]');
    var type = $el.attr('type');

    switch(type){
        case 'checkbox':
            $el.attr('checked', 'checked'); // Only works for checkboxes with unique name
            break;
        case 'radio':
            $el.filter('[value="'+val+'"]').attr('checked', 'checked');
            break;
        default:
            $el.val(val);
    }
});

我需要以某种方式更改我的复选框选择器,或者为具有共享名称的复选框创建一个新选择器。但我不知道怎么做。

---- 编辑:更新了我的代码 -------------------------- ---

我使用下面的代码让它工作,尽管现在它不能确保检查正确的名称。

// Reset form values from json object
$.each(formStateObjects[presentFormElementID], function(name, val){

    var $el = $("[name=" + name + "]");
    var type = $el.attr('type');


    // If we have a checkbox name with many values
    if(val instanceof Array) {
        checkboxArrayValues = val;
        $.each( checkboxArrayValues, function( intValue, currentValue ) {
            // Refine the selector checking for name
            var $hit = $("[value=" + currentValue + "]");
            $hit.prop('checked', true);
        });
    }

    switch(type){
        case 'checkbox':
            $el.prop('checked', true);
            break;
        case 'radio':
            $el.filter('[value="'+val+'"]').prop("checked", true);
            break;
        default:
            $el.val(val);
    }

});

【问题讨论】:

    标签: jquery json forms checkbox jquery-selectors


    【解决方案1】:

    难道这行不通吗?

    $.each(formStateObjects['product'], function (name, val) {
        var $el = $('[name^="' + name + '"]');
        var type = $el.attr('type');
    
        switch (type) {
            case 'checkbox':
            case 'radio':
                Object.prototype.toString.call(val) === '[object Array]' ? [].map.call(val, function(val){
                    $el.filter('[value="' + val + '"]').prop('checked', true);
                }) : $el.filter('[value="' + val + '"]').prop('checked', true);
                break;
        }
    });
    

    DEMO

    【讨论】:

    • 谢谢,但是当复选框的名称是 name[] 格式时,它不起作用。那是我的问题,对于每个复选框具有唯一名称的复选框,代码有效。见:jsfiddle.net/25Cn5
    • 是的,这行得通,虽然感觉有风险,因为现在它不再寻找精确匹配了。请参阅:jsfiddle.net/kLyq3 我尝试这样做以获得完全匹配: var $el2 = $("[name=" + name + '[]' +"]");但这不是一个有效的选择器。
    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2017-05-15
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多