jQuery从表单上的每个输入获取名称值

时间:2019-01-08 20:39:03

标签: jquery

我有一个由用户生成的动态表格。输入名称是动态的,基于用户先前的输入。因此,输入名称可以是任何名称。我正在尝试使用JQuery获取输入名称和输入值并将它们放置在数组中。 我的阵列空了。

我对JQuery的了解并不强,但仍然学习它,因此非常感谢您的帮助

<input type="text" class="value" name="name1" value="0">
<input type="text" class="value" name="nameA" value="2">
<input type="text" class="value" name="name44" value="8">
<input type="text" class="value" name="janedoe" value="42">

jQuery

var myArray = [];
$('input').each(function() {
    var key = $('.value').attr('name');
    myArray.push(key);
});
console.log(myArray);

控制台上的输出

0: ""
1: ""
2: ""
3: ""
length: 4
__proto__: Array(0)

我的数组显示为空。 数组的大小是正确的,每个值都为空。

2 个答案:

答案 0 :(得分:0)

只需使用Social.localUser.Authenticate((success, message) => { Debug.Log("Authentication Message: " + message); if (success) { var serverAuthCode = PlayGamesPlatform.Instance.GetServerAuthCode(); _AuthService.AuthTicket = serverAuthCode; _AuthService.Authenticate(Authtypes.Google); } else { Debug.Log("Failed authenticating with google"); } }); 方法。

serializeArray()
console.log(
  $(':input').serializeArray()
);

否则...

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="value" name="name1" value="0">
<input type="text" class="value" name="nameA" value="2">
<input type="text" class="value" name="name44" value="8">
<input type="text" class="value" name="janedoe" value="42">
console.log(
  //get the array of inputs and reduce them to a single object
  $(':input[name]').get().reduce(function(result, input){
    result[input.name] = input.value;
    
    return result;
  }, {})
);

答案 1 :(得分:0)

建议以下内容:

var myArray = [];
$('input').each(function() {
  myArray.push($(this).attr('name'));
});
console.log(myArray);

如果需要,可以这样做:

var myData = {};
$('input').each(function() {
  myData[$(this).attr('name')] = $(this).val();
});
console.log(myData);

希望有帮助。