SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru
    Join Date
    Dec 2005
    Posts
    964
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Looping through multiple formfields with javascript?

    I have a script where I can PregReplace something in a string with a defined value from my input field and it works like a charm.

    PHP Code:
    echo '<input id="pfrom" type="text" value="" name="pfrom">'
    Code JavaScript:
    function demoRegex(){
    	var txt = document.newform.thestring.value;
    	var re = new RegExp(document.newform.pfrom.value, "g");
    	newtxt = txt.replace(re,'');
    	alert(newtxt);
    }

    But what if I have multiple input field like this:
    PHP Code:
    foreach($arr as $arr1=>$value){
        echo 
    '<input id="pfrom" type="text" value="" name="pfrom[]">';

    How do I get the javascript to run through all the fields?

    Hoping for help.... Thanks in advance ;-)

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    The following fiddle should do the job for you http://jsfiddle.net/chrisupjohn/Uj4wt/

  3. #3
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You can also loop through the fields like an array:
    Code JavaScript:
    function demoRegex(){		
    	var frm = document.newform,
    		txt = frm.thestring.value,
    		frmArray = frm.pfrom,
    		i;
    	for( i = 0; i < frmArray.length; i++ ) {
    		frmArray[i].value = txt;
    	}
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •