JQuery creates realtime array from multiple inputs with same class

I have multiple inputs on a page that share the same class name authority-email

. Using jQuery, I am getting values โ€‹โ€‹from all 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 โ€‹โ€‹inside the inputs are also editable.

How do I change the input (delete, add, edit) What is the best way to pass your values โ€‹โ€‹in real time to mine emailObj

?

+3


source to share


1 answer


Your current code changes emailObj

from object to string on each loop iteration instead of changing a property of the object itself. Also note that you can use a style selector .

to match the elements with your class.

To achieve what you need you can use map()

jQuery to create an array from a group of elements in a jQuery object. Then you can assign this required property to your object emailObj

. 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, connect to the events change

and keyup

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', ... ]
});

      

+2


source







All Articles