如何从所有选定的输入字段中获取所有html5“data-”值并创建包含这些值的对象?

时间:2014-06-23 08:21:33

标签: javascript jquery html5

我有一些输入框:

<input class="form" type="checkbox" name="item1" data-value="{ 'item1':'selected', 'price': 100 }" checked="checked">
<input class="form" type="checkbox" name="item2" data-value="{ 'item2':'selected', 'price': 300 }" checked="checked">
<input class="form" type="checkbox" name="item3" data-value="{ 'item3':'selected', 'price': 600 }">
<input class="form" type="text" name="text-input" data-value="Is there any way to have this value automatically equal to the .val() of whatever the user ends of inputting in the textbox?" >

我想使用JS / jQuery来获取所有data-value并将其全部放入所选输入字段的对象中:

{
    item1 : {item1:'selected', price: 100},
    item2 : {item2:'selected', price: 300},
    text-input: "whatever the user put in"
}

现在我使用jQuery Serialize Object:

https://github.com/macek/jquery-serialize-object

但这仅适用于输入字段的value=属性(适用于无线电,文本,文本区域,复选框)。我认为您不能在正常value属性中存储哈希值,因此data-将成为我执行此操作的位置。

类似的东西:

var inputBoxContents = if ( [item is checked or selected] ) {
  $('.form').getAttribute('data-value');
}

或许可以使用预先存在的JS东西来使用?

3 个答案:

答案 0 :(得分:1)

尝试使用.each()迭代所有复选框,并使用.data()函数获取所需的值,

var xObj = {};

$(':checkbox.form:checked,:text.form').each(function(){
  xObj[this.attributes["name"].value] =
       ($(this).is(':checkbox'))? $(this).data('value'): this.value;
});

console.log(JSON.stringify(xObj)); //{item1:{item1:'selected', price: 100}, ... }

DEMO

答案 1 :(得分:1)

Demo

尝试 map() 功能:这会创建一个值数组。

var inp = $('.form:checkbox:checked').map(function(){
    return $(this).data('value');
}).get();

或者如果你需要它在对象中。

Demo

    var inp = {}; 
    $('.form:checkbox:checked').each(function(){
        inp[this.name] = $(this).data('value');
    });

Working Demo

更新(带文字输入)

$('#submit').click(function () {
    var inp = {};
    $('.form').each(function () {
        if ($(this).is(':checkbox') && this.checked) {
            inp[this.name] = $(this).data('value');
        } 
        if($(this).is(':text')){
            inp[this.name] = this.value;
        }
    });

    console.log(inp);
});

答案 2 :(得分:0)

如上所述,您可以使用jQuery data()api来访问属性。这样可以确保您的数据采用JSON格式解析为本机js对象。

或者,如果你的目标是现代浏览器 - IE11 +,firefox,chrome以及safari和Opera - 你可以使用可用的HTMLElement.dataset属性。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

当然这可能是jQuery在支持它的浏览器中使用的,然后优雅地为那些没有

的浏览器提供polyfils