Jump to content


Photo

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


  • Please log in to reply
3 replies to this topic

#1 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 06 October 2006 - 04:37 PM

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.

#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 06 October 2006 - 05:29 PM

It wouldn't let me post with the script tags. This will fetch the names.

<!-- 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"/>

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#3 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 06 October 2006 - 06:14 PM

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.
Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.

#4 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 07 October 2006 - 03:40 PM

Thanks guys :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users