Home > Blockchain >  Using map to get all values from input fields
Using map to get all values from input fields

Time:01-02

Say there are numerous <input> and I wanted all the values as an array. I thought it'd be really easy to just do $("input").map(function(obj) { $(obj).val() }), but when I get that, I'm getting the error: Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase')

This error is occuring within jQuery itself here:

var rreturn = /\r/g;

jQuery.fn.extend({
    val: function( value ) {
        var hooks, ret, isFunction,
            elem = this[0];

        if ( !arguments.length ) {
            if ( elem ) {
                hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
                ...

Any work around? Here's a fiddle: https://jsfiddle.net/jvbgo94f/1/

CodePudding user response:

A bit different than what you're looking for, but the standard way to handle this is to use FormData.

If you wrap your inputs in a form element:

<form>
  <input name="a" />
  <input name="b" />
  <input name="c" />
</form>

Then, you can do something like this:

const formData = new FormData(
    document.querySelector('form')
);

for (const [key, value] of formData) {
  console.log({key, value});
}

CodePudding user response:

You should use $(this) inside map to access that particular element.

$("#a").val("1");
$("#b").val("2");
inputs = $(".test").map(function() {
  return $(this).val();
});
console.log($(inputs));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  id="a" />
<input  id="b" />
<input  id="c" />

  • Related