Get array of values from multiple inputs using jQuery
It's not valid to have two inputs of the same name. If you want to do this, you can use <input name="titles[]">
You can try this:
<input name="titles[]">
<input name="titles[]">
<button>submit</button>
With this jQuery
// click handler
function onClick(event) {
var titles = $('input[name^=titles]').map(function(idx, elem) {
return $(elem).val();
}).get();
console.log(titles);
event.preventDefault();
}
// attach button click listener on dom ready
$(function() {
$('button').click(onClick);
});
See it working here on jsFiddle
EDIT
This answer gives you the titles in an array instead of a string using a |
separator. Personally, I think this is a lot more usable.
If you're just submitting the form and you want to support multiple values, use the .serialize
method as described in the other answer
How to get an Array with jQuery, multiple <input> with the same name
Using map:
var values = $("input[id='task']")
.map(function(){return $(this).val();}).get();
If you change or remove the id (which should be unique), you may also use the selector $("input[name='task\\[\\]']")
Working example: http://jsbin.com/ixeze3
How to get value of multiple input field with different data-id in Array using jQuery?
Give all the text box same classes so that you can access the user generated textboxes easily
Here is you HTML
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div class="Title" data-id="title_1">
<label>Additional Title</label>
<input class="textfield" type="text" value="val 1">
</div>
<div class="Title" data-id="title_2">
<label>Additional Title</label>
<input class="textfield" type="text" value="val 2">
</div>
<div class="Title" data-id="title_3">
<label>Additional Title</label>
<input type="text" class="textfield" value="val 3">
</div>
<div class="Title" data-id="title_4">
<label>Additional Title</label>
<input type="text" class="textfield" value="val 4">
</div>
<div class="Title" data-id="title_5">
<label>Additional Title</label>
<input type="text" class="textfield" value="val 5">
</div>
Here is your jquery
$( ".textfield" ).each(function( index ) {
debugger;
console.log( $(this).closest('div').attr('data-id'));
console.log( index + ": " + $( this ).val() );
});
How to get multiple values from input field in jquery?
You have to loop through all the elements to get the values from them.
You can try jQuery's .map()
and .get()
to get all the values in an array.
Demo:
var quantityArr = $('.quantity').map(function(){
return +this.value;
}).get();
console.log(quantityArr);
// if you want the value comma separated then join the array
var quantityCommaSeperatedString = quantityArr.join(',');
console.log(quantityCommaSeperatedString);
var priceArr = $('.price').map(function(){
return +this.value;
}).get();
console.log(priceArr);
// if you want the value comma separated then join the array
var priceCommaSeperatedString = priceArr.join(',');
console.log(priceCommaSeperatedString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="quantity" class="form-control quantity"value="1">
<input type="text" name="price" class="form-control price"value="10">
<input type="text" name="quantity" class="form-control quantity"value="2">
<input type="text" name="price" class="form-control price"value="20">
<input type="text" name="quantity" class="form-control quantity"value="3">
<input type="text" name="price" class="form-control price"value="30">
Get the values of all inputs with same class as an array
If all your inputs share the same class say "class1" then you can select all such inputs using this
var inputs = $(".class1");
Then you can iterate over the inputs any way you want.
for(var i = 0; i < inputs.length; i++){
alert($(inputs[i]).val());
}
Iterate Through Multiple Input Fields with JQuery
try below code snippet.
capture the data entered into all of the name fields
var value = $("input[name='name']")
.map(function() {
return $(this).val();
}).get();format them into a JSON array
var jsonStr = JSON.stringify(value);
$(document).ready(function() { $("#new_rule").click(function() { var input = "<input type='text' name='name' placeholder='name' class='form-control'>"; $("#name").prepend(input); }); $("#save").click(function() { var value = $("input[name='name']") .map(function() { return $(this).val(); }).get(); var jsonStr = JSON.stringify(value); console.log(jsonStr); });});
<!doctype html><html lang="en">
<head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> <title>Modal</title> <style media="screen"> .wrapper>div { background: #eee; padding: 1em; }
.wrapper>div:nth-child(odd) { background: #ddd; }
.wrapper { display: grid; grid-template-columns: 70% 30%; } </style></head>
<body>
<!-- Button trigger modal --> <div class="permissions"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#new"> Permissions </button> </div>
<!-- Modal --> <div class="modal fade new" id="new" tabindex="-1" role="dialog" aria-labelledby="new_modal" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="permissions">Permissions</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"><i class="fas fa-times"></i></span> </button> </div> <div class="modal-body"> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="users-tab" data-toggle="tab" href="#users" role="tab" aria-controls="users" aria-selected="true">Users</a> </li> <li class="nav-item"> <a class="nav-link" id="groups-tab" data-toggle="tab" href="#groups" role="tab" aria-controls="groups" aria-selected="false">Groups</a> </li> </ul> <div class="tab-content" id="myTabContent"> <!-- Content for the users tab --> <div class="tab-pane fade show active" id="users" role="tabpanel" aria-labelledby="users-tab"> <div class="wrapper"> <div class="users"> <u><h6>Name</h6></u> <form id="input" action="modal.php" method="post"> <span id="name"></span> </form> </div> <div class="permissions"> </div> </div> </div> <!-- Content for the groups tab --> <div class="tab-pane fade" id="groups" role="tabpanel" aria-labelledby="groups-tab"> Group Level Permissions </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-success" id="new_rule"><i class="fas fa-plus"></i></button> <button type="button" class="btn btn-primary" data-dismiss="modal" data-toggle="modal" data-target="#saved" id="save">Save</button> </div> </div> </div> </div>
<!-- Saved Modal --> <div class="modal fade" id="saved" tabindex="-1" role="dialog" aria-labelledby="saved" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Save Changes</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <p>Are you sure you would like to save the following changes?</p> <div class="wrapper"> <div class="users"> <u><h6>Name</h6></u> <span id="name"></span> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Dismiss</button> </div> </div> </div> </div>
<!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script></body>
</html>
jQuery create a real-time array from multiple inputs with the same class
Your current code is changing emailObj
from an object to a string on each iteration of the loop, instead of amending a property of the object itself. Also note that you can use the .
style selector to match elements by their class.
To achieve what you require, you can use map()
to create an array from a group of elements in a jQuery object. You can then assign this to the required property of your emailObj
object. For example:
var emailObj = {};
emailObj.emails = $("input.authority-email").map(function () {
return this.value;
});
console.log(emailObj.emails); // = [ 'a@a.com', 'b@b.com', ... ]
To update the object in 'real-time', hook to the change
and keyup
events of the inputs themselves:
var emailObj = {};
$("input.authority-email").on('change keyup', function() {
emailObj.emails = $("input.authority-email").map(function () {
return this.value;
});
console.log(emailObj.emails); // = [ 'a@a.com', 'b@b.com', ... ]
});
Related Topics
Validate Phone Number With Yup
React Native: Image Not Displaying With Dynamic/Local Uri
How to Make a Owl Carousel With Arrows Instead of Next Previous
How to Save an Image to Localstorage and Display It on the Next Page
How to Refresh Select Option List After Ajax Response
How to Compress an Image Via JavaScript in the Browser
Uncheck a Checkbox and Another Checkbox Will Untick
Preventing Viewport Resize of Web Page When Android Soft Keyboard Is Active
Angular 4: Cannot Instantiate Cyclic Dependency! Injectiontoken_Http_Interceptors
Jquery Class on Click Works on Desktop But Not Mobile
How to Get the Contextpath from Javascript, the Right Way
React Passing Import Name as Prop and Adding to Image Src
Jquery Wait Until Ajax Call Has Got Data Before Displaying
How to Toggle (Hide/Show) Sidebar Div Using Jquery
Typescript Property Does Not Exist on Type {}
I Want a Code to Fill in the Form Automatically
Stop Just One Dropdown Toggle from Closing on Click
Get Selected Item Value from Bootstrap Dropdown With Specific Id