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();
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();
Share
edited Apr 6, 2017 at 6:19
Satpal
133k13 gold badges167 silver badges170 bronze badges
asked Mar 3, 2017 at 10:41
Firoza ShaikhFiroza Shaikh
291 silver badge9 bronze badges
2
-
4
This isn't possible. The
val()
method can only return one value from one element at a time – Rory McCrossan Commented Mar 3, 2017 at 10:43 - can you tell us your purpose why you do not want to use each here ? – Mittul At TechnoBrave Commented Mar 3, 2017 at 10:53
2 Answers
Reset to default 7Use .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./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" />
var arr= $("input").map(function(){
return $(this).val();
}).get();
console.log(arr)
<script src="https://ajax.googleapis./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()