Skip to content
the poor coder

get all input values by class jquery

Poor Man
Published
Reading time
2 min read

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

Text
<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:

Text
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:

Text
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:

Text
<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:

Text
<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:

Text
<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>

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC