2011-11-24 202 views
1

我有一個有很多輸入的表單。我想獲取每個ID和值,然後將它們放在$ .load方法中。我嘗試這樣做:循環遍歷表單輸入

$("#form input").each(function() { 
    var name = $(this).attr("id"); 
    var value = $(this).attr("value"); 
    $.extend(params, { 
     name, value 
    }); 
}); 

然後用$.load("script.php", params);

但很明顯,這是行不通的。在參數中,我只有一個元素「名稱」。我不確定我也應該使用擴展方法。

+1

不會是簡單的'.serialize()''的$( '#形式')'和AJAX是什麼? –

+0

表單元素是基於它們的'name'而不是'id'屬性獲取的。 – plaes

回答

1

序列化格式,你可以使用jQuery serialize method像這樣:

var params = $("#form").serialize(); 
$.load("script.php", params); 
+0

千上傳到'.serialize()' – plaes

1

假設你想建立的是具有兩個屬性(名稱/值)對象的數組,這裏是代碼即可獲得它:

var myparams = []; 
$("form input").each(function() { 

    // build an object literal to store your values 
    var o = { 
     name: this.id, // no need to turn 'this' in a jquery object to get the ID 
     value: $(this).val() // use .val() to get the value 
    }; 

    myparams.push(o); // add to the array 
}); 
0

這似乎是工作

var params={}; 

$('input').each(function(){ 
    params[$(this).attr('id')] = $(this).val(); 
}); 

console.log(params); 

輸出

bar: "bar" 
bof: "bof" 
foo: "foo" 

看到它在這裏jsfiddle