序列化已填充或选定的字段

时间:2014-04-15 04:34:59

标签: jquery serialization

我想序列化包含填充已选择的字段(文本框复选框 selectmenu )。

HTML部分

<div id="all_field_0">
   <input type="text" name="a_0"/>
   <input type="text" name="b_0"/>
   <select name="c_0">
     <option value="1">a</option>
     <option value="2">b</option>
     <option value="3">c</option>
   </select>
   <select name="d_0">
     <option value="1">a</option>
     <option value="2">b</option>
     <option value="3">c</option>
   </select>
</div>

<div id="all_field_1">
   <input type="text" name="a_1"/>
   <input type="text" name="b_1"/>
   <select name="c_1">
     <option value="1">a</option>
     <option value="2">b</option>
     <option value="3">c</option>
   </select>
   <select name="d_1">
     <option value="1">a</option>
     <option value="2">b</option>
     <option value="3">c</option>
   </select>
</div>

jQuery部分

此代码序列化所有字段

var field_div = "";
for(var fc=0; fc<2; fc++)
{
  field_div = "#all_field_"+fc;
  $(field_div + " :input,select").serializeObject()
}

1 个答案:

答案 0 :(得分:0)

以下脚本似乎满足您的需求。每个字段只需要一些逻辑来查看是否输入了值。输入和选择最初选择它们的工作,但复选框需要1个逻辑。

var field_div = "";
for(var fc=0; fc<2; fc++)
{
  field_div = "#all_field_"+fc;

  //Check to see if input has value
  if($(field_div + " :input,select").val()) {
    //Field has something
    $(field_div + " :input,select").serializeObject(); //Serialize and store somewhere
  } else {
    //Field doesn't have something
  }

  //Check for selected checkbox
  if($(field_div + " :checkbox:checked").length > 0) {
     //Checkbox is checked
     $(field_div + " :checkbox:").serializeObject(); //Serialize and store somewhere
  } else {
     //Checkbox is not checked
  }

}