Jump to content

Archived

This topic is now archived and is closed to further replies.

Kris

Finding all form inputs whose name/id begins with...

Recommended Posts

I'm creating some form inputs dynamically with php and naming them in a box_n fashion (n being an incrementing int). Any ideas on how I would go about fetching the contents of all of these inputs with JavaScript? Do I somehow loop through all form objects and check a substring-ed name/id for a match, or is there a simpler way?

Many thanks in advance.

Share this post


Link to post
Share on other sites
It wouldn't let me post with the script tags. This will fetch the names.

[code]
<!-- javascript -->
function find_boxes() {
var boxes = new Array();
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var name = inputs[i].name;
if (name.match(/^box_\d+$/)) {
boxes.push(name);
}
}
alert(boxes);
}
<!-- /javascript -->
<form name="test_form">
<input name="box_1"/>
<input name="box_2"/>
<input name="box_3"/>

<input name="name"/>
<input name="address"/>
<input name="etc"/>

<input name="box_4"/>
<input name="box_5"/>
<input name="box_6"/>
</form>
<input type="button" onclick="javascript:find_boxes()" value="Find the boxes"/>
[/code]

Share this post


Link to post
Share on other sites
Yup, there really isn't another way other than actually checking each one; note that you shouldn't have the javascript: in a JS handler.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.