Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery create a real-time array from multiple inputs with the same class

I have multiple inputs on a page that all have the same class name authority-email. Using jQuery I get the values from all the inputs using the following:

var emailObj = {};
$("input[class=authority-email]").each(function () {
  var email = $(this).val()

  emailObj = email;

  console.log(emailObj);
});

These inputs can be removed and added to the DOM using jQuery. The values within the inputs are also editable.

As the input changes (remove, add, edit) What is the best way to pass their values in real-time to my emailObj?

like image 997
Thomas Taylor Avatar asked Aug 28 '26 09:08

Thomas Taylor


1 Answers

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); // = [ '[email protected]', '[email protected]', ... ]

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); // = [ '[email protected]', '[email protected]', ... ]
});
like image 75
Rory McCrossan Avatar answered Aug 30 '26 02:08

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!