4

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/

2
  • Please provide a minimal reproducible example. Commented Jan 1, 2022 at 6:10
  • @kiner_shah updated Commented Jan 1, 2022 at 6:17

2 Answers 2

1

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 class="test" id="a" />
<input class="test" id="b" />
<input class="test" id="c" />

Sign up to request clarification or add additional context in comments.

2 Comments

interesting... do you know why map passing & using each obj as i was doing fails?
@james, there are two ways to use map - first way and second way. I used second way.
0

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});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.