Solved

How do I get the iterated id value for form validation in Javascript?

Posted on 2014-02-25
10
330 Views
Last Modified: 2014-02-27
Hi everybody!

I have a form in which I have a for-loop in php to generate multiple text fields. Since I need to validate(regex) the input fields, I do not know how to use the document.getElementById('textfield<?php echo $i; ?>').

I know this is wrong, and I may need to get something like getElementById('textfield'+$i) ... I have tried a lot but I am an absolute beginner in Javascript and so am clueless!!!

Do I also need to use a for loop in the javascript file to generate the $i or something????

I do know that I do not want to get all the fields together by using:
getElementById() OR getElementsByTagName() and then validate whether they are empty fields by clicking onsubmit().

I need to check each input against a specific regex pattern so I need to isolate the value of each iterated id so I do the regex checking.

Can anyone help me please?

Thanks in advance!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <p>
    <?php 
for ($i=1;$i<=3;$i++){
?>
        <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" />
    </br>
  <?php  } ?>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
</body>
</html>

Open in new window

forumPosting.php
0
Comment
Question by:786aslamkhan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 39886265
Here is some sample code to get you started
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function validate()
{
 // GET ALL INPUT ELEMENTS INTO AN ARRAY
  var inps=document.getElementsByTagName("input");

  // SAMPLE VALIDATION - ONLY ALLOWS DIGITS
  var regx = /[0-9]+/;

  // LOOP THROUGH ALL ITEMS IN ARRAY
  for(i = 0; i < inps.length; i++) {

    // If this is a submit button then ignore it.
    if (inps[i].type == 'submit') continue;

    // TEST THE VALUE OF THE FIELD AGAINST OUR REGX
    if (!regx.test(inps[i].value)) {
      // SHOW THE ERROR
      alert('failed validation for ' + inps[i].value);

      // RETURN FALSE TO TELL THE FORM NOT TO SUBMT
      return false;
    }
  }

  // ALL OK SUBMIT ALLOWED
  return true;
}

</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="" onsubmit="return validate();">
  <p>
    <?php 
for ($i=1;$i<=3;$i++){
?>
        <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" />
    </br>
  <?php  } ?>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
</body>
</html>
           

Open in new window

The above is provided for illustration purposes. There are validation libraries out there that you could also consider.
0
 

Author Comment

by:786aslamkhan
ID: 39887997
@julianH: Thank you for reading my question and responding! I'm working on your suggestions and will get back to you as soon as I can. Thank you for your interest and time!

By validation libraries do you mean various posts on various sites or dedicated libraries like jsclasses.org. May I please request you to recommend some? Thanks!
0
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 39888089
I meant javascript libraries that do form validation for you.

One option is to look at JQuery and the JQuery valiation (http://jqueryvalidation.org/) plugin

If you want to stay with plain javascript here are some links

http://parsleyjs.org/
http://rickharrison.github.io/validate.js/
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:786aslamkhan
ID: 39888176
@julianH: Thanks a ton! Very helpful of you! I have noted the links. Thanks!

I'm still working on my solution... Your suggestions have very useful and the code and the approach work. I'm just trying to get a text / message prompt instead of the alert (showing the error). My issue is that the prompt field is also iterated into corresponding label_ids.
0
 
LVL 9

Expert Comment

by:Sar1973
ID: 39888229
I'd also suggest to use different names and ids for your objects, and also not to use the name of objects (such as "button") as names and ids.
0
 

Author Comment

by:786aslamkhan
ID: 39888369
@Sar1973: Thank you for your suggestions. I shall be cautious not to use such names as you have warned me about,  although I have used unique ones so far. Thank you!
0
 

Author Comment

by:786aslamkhan
ID: 39891141
@julianH:

Your suggestions are very useful and when applied they work perfectly.

My issue, which takes me back to my question is "to check each input against a specific regex pattern so I need to isolate the value of each iterated id so I do the regex checking".

 Also as I have indicated in my earlier post that "I'm just trying to get a text / message prompt instead of the alert (showing the error). My issue is that the prompt field is also iterated into corresponding label_ids. ".

What I'm trying to achieve is the same effect as in the demo in the site (http://jquery.bassistance.de/validate/demo/) that the link you had kindly posted for me (on the top of the page with a lime-green background).

How do we achieve that where the text field has been iterated as in my case (code provided earlier). I have tried everything I could think of with my limited exposure to Javascript and failed!


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function producePrompt(message,promptLocation,color){
		document.getElementById(promptLocation).innerHTML=message;
		document.getElementById(promptLocation).style.color=color;
		}


 function validate()
{
 // GET ALL INPUT ELEMENTS INTO AN ARRAY
 
  var inps=document.getElementsByTagName("input");
  
  // SAMPLE VALIDATION - ONLY ALLOWS DIGITS
  var regx = /^[a-zA-Z0-9]+$/;
	
	 // LOOP THROUGH ALL ITEMS IN ARRAY
  for(i = 0; i < inps.length; i++) {
  
    // If this is a submit button then ignore it.
    if (inps[i].type == 'submit' ) continue;
	
	if (inps[i].length == 0 || inps[i].value == ""){
	
		producePrompt("","txtfield_prompt","red");
			return false;
		}

    // TEST THE VALUE OF THE FIELD AGAINST OUR REGX
    if (!regx.test(inps[i].value)) {
      // SHOW THE ERROR
     // alert('failed validation for ' + inps[i].value);
	
producePrompt("'Alphanumeric data only! ","txtfield_prompt","red");
      // RETURN FALSE TO TELL THE FORM NOT TO SUBMT
      return false;
    }
	if(regx.test(inps[i].value)) {

producePrompt("Valid input","txtfield_prompt","green");
  
      return true;
    }
    }
    }
		
</script>

<!--<form id="someForm" action="#" method="post" onsubmit="return false">
 <span id="inputFields">
  <p>
   <input type="text" name="textfield1"/>
  </p>
  <p>
   <input type="text" name="textfield2"/>
  </p>
  <p>
   <input type="text" name="textfield3"/>
  </p>
 </span>
 <input type="submit" />
</form> -->
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="" >
 <span id="inputFields"> <p>
    
   <label id="txtfield_prompt" class="style27"> </label></br>
  
	<?php 
for ($i=1;$i<=3;$i++){
?>
    
    <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" onkeyup="validate()"/>
    </br>
  <?php  } ?>
  </p>
  </p>
  </span>
  <p>
  
    <input type="submit" name="button" id="button" value="Submit" onclick="checkVal()"/>
    <input type="reset" name="button2" id="button2" value="Reset" />
  </p>
</form>
</body>
</html>

Open in new window

0
 
LVL 57

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 39891270
Please take a look at the code below. No time to comment - there were several things wrong with your code but this gives an example of what I think you were trying to achieve.
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function producePrompt(message,promptLocation,color)
{
  document.getElementById(promptLocation).innerHTML=message;
  document.getElementById(promptLocation).style.color=color;
}


function validate()
{
 // GET ALL INPUT ELEMENTS INTO AN ARRAY
  var inps=document.getElementsByTagName("input");
  // SAMPLE VALIDATION - ONLY ALLOWS DIGITS
  var regx = /^[a-zA-Z0-9]+$/;
	
	 // LOOP THROUGH ALL ITEMS IN ARRAY
  for(i = 0; i < inps.length; i++) {
 
    // If this is a submit button then ignore it.
    if (inps[i].type == 'submit' ) continue;
	producePrompt("", "txtfield" + (i+1) + "_prompt", "");
	if (!regx.test(inps[i].value)){
      producePrompt("'Alphanumeric data only! ","txtfield" + (i+1) + "_prompt","red");
      return false;
	}

    // TEST THE VALUE OF THE FIELD AGAINST OUR REGX
    if (!regx.test(inps[i].value)) {
      // SHOW THE ERROR
     // alert('failed validation for ' + inps[i].value);
	
      // RETURN FALSE TO TELL THE FORM NOT TO SUBMT
      return false;
    }
  }
  return false;
}

function alphaNum(evt)
{
	this.value = 'fred';
}		

</script>
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" onsubmit="validate(); return false;">
 <div id="inputFields">
    
   <label id="txtfield_prompt" class="style27"> </label><br />
  
<?php 
for ($i=1;$i<=3;$i++) :
?>
    
    <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" onkeyup="this.value=this.value.replace(/[^a-zA-Z0-9]/g, '')"/><div class="prompt" id="txtfield<?php echo $i;?>_prompt"></div>
    <br/>
	
<?php
endfor 
?>
  </div>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
    <input type="reset" name="button2" id="button2" value="Reset" />
  </p>
</form>
</body>
</html>

Open in new window

0
 

Author Closing Comment

by:786aslamkhan
ID: 39891438
@julainH:
Although very close to what exactly I was trying to achieve, this solution is probably even better than my goal. It was an exceptional experience and opportunity to learn from you, a true master and genius!

Thank you very much!

I will, however, try and use all that I have learnt from you through this question in trying to achieve what I originally set out for!

Thank you for your time, advice and code julianH!
0
 
LVL 57

Expert Comment

by:Julian Hansen
ID: 39891495
You are most welcome - thanks for the points and good luck.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Foolproof security solutions has become one of the key necessities of every e-commerce or Internet banking website. If you too own an online shopping site then its vital for you to equip your web portal with customer security features that can allow…
A publishing tool, a Version Control System, or a Collaboration Platform! These can be some of the defining words for the two very famous web-hosting Git repositories: Bitbucket and Github. Git is widely used amongst the programmers and developers f…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Use Wufoo, an online form creation tool, to make powerful forms. Learn how to choose which pages of your form are visible to your users based on their inputs. The page rules feature provides you with an opportunity to create if:then statements for y…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question