Strannik Strannik - 11 days ago 6
jQuery Question

How to get the value of all inputs in a form

Code:

<form name="newform" action="test.php" method="post" class="form-horizontal input-prepend" id="newform">

<div class="form-group">
<label class="control-label" for="test1">test1</label>
<input type="text" name="test1" class="form-control" id="test1" placeholder="">
</div>

<div class="form-group">
<label class="control-label" for="test2">test2</label>
<input type="text" name="test2" class="form-control" id="test2" placeholder="">
</div>

<div class="form-group">
<label class="control-label" for="test3">test3</label>
<input type="text" name="test3" class="form-control" id="test3" placeholder="">
</div>

<div class="form-group">
<label class="control-label" for="test1">test4</label>
<input type="text" name="test4" class="form-control" id="test4" placeholder="">
</div>

<div class="form-group">
<label class="control-label" for="test5">test5</label>
<input type="text" name="test5" class="form-control" id="test5" placeholder="">
</div>

</form>


In order to get an input's value, we can use its
id
, for example
alert($("#test5").val())
, but how to get the input value sequentially from the beginning of the form when we do not know the
id
of the input?

For my test code I can get value using code:

var value1 = $("test1").val();
var value2 = $("test2").val();
var value3 = $("test3").val();
var value4 = $("test4").val();
var value5 = $("test5").val();


Does anyone have any ideas about how to get values when we don't know an input's
id
?

Answer

Try:

$('form').serialize();

or:

var values = [];
$('input').each(function() {
    values.push($(this).val());
});