Reputation: 29
I want to get the values of all input at once using one .val()
function in jQuery.
$("#txt1").val();
$("#txt2").val();
$("#txt3").val();
Instead of this I want to write the below code
$("#txt1, #txt2, #txt3").val();
Upvotes: 2
Views: 7366
Reputation: 15555
var arr= $("input").map(function(){
return $(this).val();
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="1">
<input type="text" value="11">
<input type="text" value="11">
You need to loop through them try using .map()
Upvotes: 1
Reputation: 21489
Use .map()
to convert selected input to value of them and then use Array.prototype.join()
to convert array result to string.
var values = $("#txt1, #txt2, #txt3").map(function(){
return this.value;
}).get().join(" ");
console.log(values)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt1" value="a" />
<input type="text" id="txt2" value="b" />
<input type="text" id="txt3" value="c" />
Upvotes: 7