我的表单应包含key=>value
对,其中key
应为表单的label
,value
应为用户输入的详细信息,
我的问题是获取该字段的name
而不是label
,
预期output
:
ENTER YOUR AGE:25
但我得到这样的输出:
name-preview : 25;
如何实现预期的output
?
var result = [];
$('div label').each(function() {
var $this = $(this);
var label = $this.text();
//console.log(label);
value = $this.siblings().attr('value');
//console.log(value);
result.push({
label: label,
value: value
});
});
console.log(result);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form action="uploaddata.php" method="POST">
<div class="form-group">
<label for="text-1483332101835-preview" class="fb-text-label">enter your age:</label>
<input type="text" class="form-control" name="age" value="25" id="mobNum">
</div>
&#13;
&GT;
我如何为此elements
:https://jsfiddle.net/ktgmtwd7/1/
答案 0 :(得分:0)
尝试一下-更改输入值时,结果数组将自动更新:
var result = [];
var input;
$('div label').each(function() {
var $this = $(this);
var label = $this.text();
input = $this.next();
result.push({
label: label,
value: input.val()
});
console.log(result);
$this.next().on('keyup', function() {
result = [];
result.push({
label: label,
value: input.val()
});
console.clear()
console.log(result);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="uploaddata.php" method="POST">
<div class="form-group">
<label for="text-1483332101835-preview" class="fb-text-label">enter your age:</label>
<input type="text" class="form-control" name="age" value="25" id="mobNum">
</div>
</form>
<h3></h3>