最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get values of multiple input in one string by ".val()" using jquery? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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./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()

发布评论

评论列表(0)

  1. 暂无评论