繁体   English   中英

如何使用jQuery基于用户输入创建JavaScript数组

[英]How to create javascript array based on user input using jQuery

我已经动态加载复选框字段,如何根据用户选择将其发送到服务器。

例如,我关注文档,

<label>Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />

<label>Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />

假设如果用户为每个选择了前两个值,那么我需要像

response[0][0]=199; // Id
response[0][1]=['Apple','Mango']; //values
response[1][0]=200
response[1][1]=['Red','Blue'];

我尝试了现有帖子中建议的一些方法,但未能实现我想要的方法。

您可以在html中进行一些小的更改,然后使用.map()

<label class="set" data-id="199">Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label class="set" data-id="200">Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />

然后

var array = $('.set').map(function () {
    var $this = $(this),
        id = $this.data('id'),
        array = [id];

    array.push($('input[name="set_' + id + '\\[\\]"]').filter(':checked').map(function () {
        return this.value;
    }).get())
    return [array]
}).get()

演示: 小提琴

另一个解决方案:

<lable>Set1</lable>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />

<input type="button" value="check" class="js-submit">

JS:

$(".js-submit").on("click", function(){
    var a = $("input[type='checkbox']:checked");
    var values = {};
    a.each(function(){
        var value = $(this).val();
        var name = $(this).attr("name");
        if(!values[name]) values[name] = [];
        values[name].push(value)
    });
    console.log(values)
});

演示

为了进一步说明我的意见,下面是我的处理方法...假设您将其作为ajax请求发送,我仍将这些元素包装在form元素中,并将其用作起点建立我们将要发送的对象...

var myForm = document.getElementById('formID').elements,//get all input nodes
data = {},temp;
for (var i=0;i<myForm.length;++i)
{
    temp = myForm.item(i).name.replace(/[[]]/g,'');//replace square brackets
    if (!data[temp])
        data[temp] = [];//create array if key does not exist
    if (myForm.item(i).checked)//for checkboxes
        data[temp].push(myForm.item(i).value);
}

这是基本设置。 如果需要,可以添加检查并进一步定制它,以便可以处理各种类型的输入字段,但从本质上讲,它可以归结为这一点。
您可能还希望在myForm.elements NodeList上使用Array.prototype.forEach ,并使用回调使代码保持整洁。
这是相同代码的稍微有用的版本的示例:

btn.addEventListener('click', function()
{
    var data = {};
    Array.prototype.forEach.call(frm.elements, function(item)
    {
        var temp;
        if (item === btn) return;//don't includ the button element
        if (item.type === 'checkbox' && !item.checked ) return;//not checked, ignore
        if (item.name.match(/[[]]/))
        {
            temp = item.name.replace(/[[]]/g, '');
            if (!data[temp]) data[temp] = [];//if property does not exist, make an array
            data[temp].push(item.value);
            return;
        }
        //normal elements:
        data[item.name] = item.value;
    });
    //ajax request using data variable goes here!
    console.log(data);
},false);

是它的小提琴

首先,感谢所有对此问题给出答案的人。 我已经针对这个问题提出了自己的解决方案,但是没有您的帮助就不可能实现,尤其是

       var checkBoxArray = {};

        $.each($("input[name^='set_'][type='checkbox']:checked"), function(i, item) {

            var Id = item.name.replace(/^(set_)|[\[\]]/g, "");
            var value = $(item).val();         

            if(!checkBoxArray[Id]) 
               checkBoxArray[Id] = [];
             checkBoxArray[Id].push(value)
        });                        

         $.map(checkBoxArray, function(value, index) {
           reponse.push([index, value]);
         });

它对我有用,建议上面的代码片段中是否有不正确的地方。

暂无
暂无

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

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