2

I have a function in Javascript that generates dynamic <input> elements when a button is clicked. The elements get structures as such:

<input name="array[0]" value="Value" />
<input name="array[1]" value="Value" />

What I need to do is via jQuery, replace the value of each of these elements. This would be pretty simple if the name was something like name="array[]", as I could be able to call:

$("input[name='array[]']").each(function(e) {
  $(this).val("New Value");
})

To replace them all, but this functionality doesn't work with these name="array[N]" inputs. I wish I could use that first method, but I need the [N] indices for something later on the backend, and changing that would destroy almost all functionality.

Also, I've made a JSFiddle demonstrating this issue, feel free to debug with it.

JSFiddle

1

3 Answers 3

3

You can use the attribute starts with, attribute ends with, or attribute contains selectors

$("input[name^='array[']") // starts with
$("input[name$=']'")       // ends with, probably not very useful here
$("input[name*='array']")  // contains
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks for that explanation! No one ever showed me those, would have been nice :P
2

You could use the attribute starts with selector to match the inputs.

http://api.jquery.com/attribute-starts-with-selector/

$("input[name^='array']").each(function(e) {
  $(this).val("New Value");
});

Comments

2

To directly answer your question, you can use the starts with (^) selector "input[name^='second[']". However I would recommend using a class and then using the apropriate selector

DEMO : http://jsfiddle.net/trex005/46o1npab/8/

1 Comment

Yeah, I suppose I could have used a class. This is my coworker's code and I'm not 100% sure where these inputs are coming from, which is why I opted to work with what I had. Thanks though!

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.