2

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();
2
  • 4
    This isn't possible. The val() method can only return one value from one element at a time Commented Mar 3, 2017 at 10:43
  • can you tell us your purpose why you do not want to use each here ? Commented Mar 3, 2017 at 10:53

2 Answers 2

7

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" />

Sign up to request clarification or add additional context in comments.

1 Comment

I guess this makes sense.
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.