2014-09-19 55 views
1
var checkedValues = $('.required:checked').map(function() { 
       return this.value; 
      }).get(); 

      var arr = new Array(10); 
      alert(checkedValues); 
      alert("number of values in it " +checkedValues.length); 
      if (checkedValues.length > 1) { 

       alert("I am inside if "); 
       arr = checkedValues.split(','); 

       alert("I am done with the split "); 
      } 
      else { 
       arr = checkedValues; 
       alert("No split needed "); 
      } 





       $.getJSON('@Url.Action("testcata", "home")' + + '?Type=' + "@(Session["typ"])" + "&city=" + "@(Session["cit"])" + "&chkd=" + checkedValues, 


      function (data) { 

          //code 
         }) 

In controller : 
public ActionResult testcata(string Type, int? city, int[] chkd) 
    { 
     //code 
    } 

我想獲取檢查框的值,並將它們存儲在數組中,然後通過json函數發送給控制器。警報(「我已完成拆分」)未顯示。請幫幫我。如何解析表單數據以在jQuery中使用JSON?

+1

使用控制檯日誌而不是警報 – 2014-09-19 12:56:52

+1

可以顯示html嗎? – Sablefoste 2014-09-19 12:57:21

+7

'checkedValues'已經是一個數組。你想要分裂什麼? – 2014-09-19 12:59:28

回答

1

看一看.serializeArray()

var checkedValues = $('.required:checked').serializeArray(); 

它返回一個數組準備JSON,像這樣:

[ 
    { 
    name: "a", 
    value: "1" 
    }, 
    { 
    name: "b", 
    value: "2" 
    }, 
    { 
    name: "c", 
    value: "3" 
    }, 
    { 
    name: "d", 
    value: "4" 
    }, 
    { 
    name: "e", 
    value: "5" 
    } 
] 
0

split適用於字符串。您可以使用split on each array index而不是whole array

如果你真的想拆分數組checkedValues,然後遍歷這個數組然後use split on each index

這樣的:

for(var i=0; i< checkedValues.length;i++){ 

var arr = checkedValues[i].split(','); 
// use arr for requrement. 

} 
+1

你應該在你的回答中包括什麼需要改變以實現OP正在嘗試什麼 – Alex 2014-09-19 13:09:02

+0

爲什麼投票我正在進行一些編輯。 – 2014-09-19 13:11:56

0

嘗試

// array of values 
var arr = []; 
$(".required") 
    .on("change", function (e) { 
    // `checked` `.required` elements 
    var checkedValues = $(this).prop("checked"); 
    // `if` `checkedValues` (any `required` elements `checked`) , continue 
    if (checkedValues) { 
     // populate `arr` with `.required` `checked` values 
     arr.push(checkedValues); 
     // do stuff with `arr` 
     // `console.log` values in `arr` , `arr` length 
     console.log("array of values: " + arr 
        , "array of values length: " + arr.length); 
    }; 
}); 

jsfiddle http://jsfiddle.net/guest271314/d332nfkh/

+0

console.log沒有顯示任何東西,當我檢查複選框,然後運行 – 2014-09-20 04:39:00

+0

不確定是什麼問題,在每個複選框檢查,數組的值:真值數組的長度:1',數組值:true,真值數組長度:2',等等在jsfiddle中記錄到'console'。 – guest271314 2014-09-20 14:17:57