get all input values by class jquery

Get all input values by class jQuery

If you need to get the value of all input fields with a specific class, jQuery makes it easy via the .val() method. Here's how:

First, give all the input fields you want to target the same class. For example, let's say you want to target all input fields with the class "my-input":

<input type="text" class="my-input">
<input type="text" class="my-input">
<input type="text" class="my-input">
<input type="text" class="my-input">

Then, use the .map() method in combination with .get() to create an array of all the values:

var myValues = $('.my-input').map(function() {
  return $(this).val();
}).get();

This will create an array called "myValues" containing all the values of the input fields with the class "my-input". You can then use this array however you need.

Another way to do it:

You can also loop through all the input fields with the class "my-input" using the .each() method and push their values into an array:

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

This will achieve the same result as the previous example.

Here's what the final code would look like in HTML:

<div class="my-inputs">
  <input type="text" class="my-input">
  <input type="text" class="my-input">
  <input type="text" class="my-input">
  <input type="text" class="my-input">
</div>

<script>
  var myValues = $('.my-input').map(function() {
    return $(this).val();
  }).get();
  console.log(myValues);
</script>

Make sure to include the jQuery library before your script tag:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

And don't forget to add the highlight.js CSS and JS files to your HTML file if you want syntax highlighting:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.2/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.2/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe