为什么jquery serialize()无法解析用户定义的属性?

时间:2016-08-09 05:42:32

标签: javascript jquery

我的代码是

    $("#section-form").submit(function (e) {
        e.preventDefault();
        var get_data = JSON.stringify($('#common-element-form').serializeArray());
        console.log(get_data);
        var common_element_data = JSON.parse(get_data);
        $(common_element_data).each(function (idx, val) {
            console.log(common_element_data);
        });

    });
<form id="common-element-form">

                <div class="form-group input select" id="campus-select-parent-div">
                    <label for="campus-type" class="col-sm-3 control-label text-right">Campus Type</label>

                    <div id="container-campus-select" class="col-sm-9">

                    <select class="form-control" name="campus-select" id="campus-select"><option value="">Select</option><option value="1">Collectorate Balika Biddya Niketan</option><option value="27">qwe</option></select></div>
                </div><br><br><br>

                <div class="form-group input select">
                    <label for="shift-select" class="col-sm-3 control-label text-right">Shift Type</label>

                    <div id="container-shift-select" class="col-sm-9 ">

                        <select name="shift-select" id="shift-select" class="form-control">
                        <option value="">Select</option><option value="10">Day</option><option value="29">Night</option></select>
                    </div>
                </div><br><br>
                <div class="form-group input select">
                    <label for="medium-select" class="col-sm-3 control-label text-right">Medium Type</label>

                    <div id="container-medium-select" class="col-sm-9 "><input class="form-control" id="medium-select" type="text" medium-element-id="16" value="700"></div>
                </div>
            </form>

但它正在显示

  

未捕获错误:语法错误,无法识别的表达式:campus-select = 1&amp; shift-select = 10

这意味着它无法解析输入

<input class="form-control" id="medium-select" type="text" medium-element-id="16" value="700">

任何建议?

1 个答案:

答案 0 :(得分:1)

试试这个

   $(document).ready(function() { 
      $("#section-form").submit(function(e) {
         var get_data = $("#common-element-form").serializeArray();
         $.each(get_data, function (index, elem) {
           alert("name: " + elem.name)
           alert("value: " + elem.value)
           alert($('[name='+ elem.name +']').data("medium-element-id"))
         });
         e.preventDefault();
      });
   });

您无法从SerializeArray()获取用户定义的属性值。而是尝试其他替代方案,例如

var data_arr=$('input').map(function(){ return $(this).data('medium-element-id');}).get(); 
console.log(data_arr); 

并将您的medium-element-id属性更改为数据属性