0

I have a WebForm with dynamically created fields like:

name_1
name_2
name_3

Using JQuery it got them in a Object using something like:

var inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
        formObj[input.name] = input.value;
    });

Now I want to dynamically access the values in the formObject in a later step, but I'm stuck on how to access the variable names in a dynamic manner?

This and others did not work:

var name = formObj.name + '_' + index;

Any idea? Thanks.

Liam
  • 27,717
  • 28
  • 128
  • 190
Stef
  • 593
  • 3
  • 10
  • 23
  • you want the jquery [starts with selector](https://api.jquery.com/attribute-starts-with-selector/) `$( "[name^='name_']" )` – Liam May 23 '17 at 09:56
  • Possible duplicate of [jquery selector for id starts with specific text](https://stackoverflow.com/questions/23223526/jquery-selector-for-id-starts-with-specific-text) – Liam May 23 '17 at 09:56

1 Answers1

1

Bracket notation allows you to access properties dynamically

var name = formObj['name_' + index];

You're actually doing exactly that in your existing code: formObj[input.name] = input.value

Lennholm
  • 7,205
  • 1
  • 21
  • 30
  • [starts with selector or a class](https://stackoverflow.com/a/23223564/542251) would be a much better solution – Liam May 23 '17 at 09:57
  • @Liam That's for DOM nodes, OP is storing the values from form elements in a plain JS object for use at a later time. jQuery selectors don't apply here. – Lennholm May 23 '17 at 10:03
  • Dull. Sorry, right. Maybe I should have a break. Thanks. – Stef May 23 '17 at 10:03