...

View Full Version : Looping through formfields?



jmansa
01-07-2012, 11:34 AM
I have a script where I can PregReplace soething in a string with a defined value from my input field and it works like a charm.


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

But what if I have multiple input field like this:

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 ;-)

Amphiluke
01-07-2012, 12:03 PM
Firstly get all the fields named "pfrom[]". Then loop through them as needed.


<script>
function demoRegex(val){
var txt = document.newform.thestring.value;
var re = new RegExp(val, "g");
newtxt = txt.replace(re,'');
alert(newtxt);
}

function foo() {
var pfrom = document.getElementsByName("pfrom[]");
for (var i = 0, len = pfrom.length; i < len; i++) {
demoRegex(pfrom[i].value);
}
}
</script>


To answer more specifically one needs to know whether you want to apply all N regular expressions to the same initial string and get N resulting strings, or you wish to pass this initial string through all the RE sequentially and get a single resulting string.

jmansa
01-07-2012, 12:09 PM
To answer more specifically one needs to know whether you want to apply all N regular expressions to the same initial string and get N resulting strings, or you wish to pass this initial string through all the RE sequentially and get a single resulting string.

Well I want to get a single string.

Amphiluke
01-07-2012, 12:14 PM
In that case the script may look like this:

<script>
function demoRegex(){
var pfrom = document.getElementsByName("pfrom[]"),
txt = document.newform.thestring.value,
re;
for (var i = 0, len = pfrom.length; i < len; i++) {
re = new RegExp(pfrom[i].value, "g");
txt = txt.replace(re,'');
}
alert(txt);
}
</script>

jmansa
01-07-2012, 12:20 PM
In that case the script may look like this:

<script>
function demoRegex(){
var pfrom = document.getElementsByName("pfrom[]"),
txt = document.newform.thestring.value,
re;
for (var i = 0, len = pfrom.length; i < len; i++) {
re = new RegExp(pfrom[i].value, "g");
txt = txt.replace(re,'');
}
alert(txt);
}
</script>

Oh yes.... Thanks alot... Your the champ ;-)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum