Hi,

I have a form where the users can add "name" and "id" fields by clicking on the "Add" button.

The input fields look like this (each pair is a row):

<input name="name_1" id="name_1" /> <input name="id_1" id="id_1" />
<input name="name_2" id="name_2" /> <input name="id_2" id="id_2" />
...

The 'name' and 'id' attributes are dynamically named with the integer increasing in value, by 1, for every new field.

Please can someone help me with validating these fields.
Note: As this is client controlled, I do not know how many rows there will be...

Thanks in advance
Lewilaloupe

Recommended Answers

All 2 Replies

Hi,
Simply using input type text alone, u may use table , and place input type text as one column of a row of a table. Then u can get the table row length easily. Then using for loop u can easily get names and validate each field.

Alternatively you can also use this javascript to get all the input elements having name matching a particular regular expression and process on it

<script language="JavaScript">
  <!--

	//set the array filter function if it is not present
	if (!Array.prototype.filter)
	{
	  Array.prototype.filter = function(fun /*, thisp*/)
	  {
		var len = this.length;
		if (typeof fun != "function")
		  throw new TypeError();

		var res = new Array();
		var thisp = arguments[1];
		for (var i = 0; i < len; i++)
		{
		  if (i in this)
		  {
			var val = this[i]; // in case fun mutates this
			if (fun.call(thisp, val, i, this))
			  res.push(val);
		  }
		}

		return res;
	  };
	}


	//call this method for validation
	function validateInput(){
		//Get all the input elements and push them into an array
		var inputs = document.getElementsByTagName('input');
		var inputArr = new Array();		
		for(var i=0; i<inputs.length; i++){
			inputArr.push(inputs[i]);
		}
		
		//Now filter the array to get the list of input elements having the name attribute starting with 'name_'
		var inputNames = inputArr.filter(
			function(elt){
				return elt.name && elt.name.match(/^name_/);
			}
		);
		//process the input elements starting with 'name_'
		for(var i=0; i<inputNames.length; i++){
			alert(inputNames[i].value);
		}


		//Now filter the array to get the list of input elements having the name attribute starting with 'id_'
		var inputIds = inputArr.filter(
			function(elt){
				return elt.name && elt.name.match(/^id_/);
			}
		);
		//process the input elements starting with 'id_'
		for(var i=0; i<inputIds.length; i++){
			alert(inputIds[i].value);
		}
	}
  //-->
  </script>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.