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?
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]', ... ]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With