简体   繁体   中英

Getting an array of input values with Jquery

I am selecting all input elements with class "img-title" in order to get an array with the current value of these inputs:

var values = []
for (let element of $(".img-title")){ 
   values.push( element.val() ) }

But this doesn't work, because the elements of $(".img-title") are not the references to the inputs as I expected, but the html code, so val() rises an error. Is there a simple way to get the array with the current values of the inputs with class "img-title" ?

When you use for..of over a jQuery collection, the items you get back are the elements themselves, not a jQuery collection which contains that element. Either turn the element into a jQuery collection first before calling .val() on it:

const values = []
for (const element of $(".img-title")){ 
  values.push( $(element).val() )
}

Or, access the property on the native element just with .value :

const values = []
for (const element of $(".img-title")){ 
  values.push( element.value )
}

Or, consider using .map instead:

const values = $(".img-title")
  .map(function() {
    return $(this).val();
  })
  .get();

(make sure to use .get() at the end, to get the array, rather than the jQuery collection)

Or, avoid jQuery entirely if you want, no need to include a big library for something as simple as this:

const values = Array.prototype.map.call(
  document.querySelectorAll('.img-title'),
  element => element.value
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM