...

View Full Version : javascript getelementbyID within a loop problem



addyking
03-09-2012, 07:16 PM
I have the following code...the getelementbyId works fine it changes the value in the textfield aswell....but only in the first retrieved record...It is not working in any of the other records that are showed.

Code is here:

<?php

include("../connection/conn.php");



?>
<script type="text/javascript">
function notEmpty(){
var myTextField = document.getElementById('myText');
document.getElementById('myText').innerHTML = myTextField;

if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
}
</script>

</head>

<body>
<?php

$sql=mysql_query("select * from menuscript");

while($row=mysql_fetch_array($sql))
{

?>

<div class="mine">
<?php echo $row['author'];?>


<form>
<input type='text' id='myText' />
<input type='button' onclick="notEmpty();" value='Form Checker' /> </form>

</div>

<?php
}?>

addyking
03-09-2012, 07:25 PM
http://i39.tinypic.com/ru9v9u.png

felgall
03-09-2012, 07:54 PM
Your PHP loop is creating multiple

<input type='text' id='myText' />

tags and so is generating invalid HTML. Each id within a web page MUST have a different value. You can only have one id='myText' per page.

addyking
03-09-2012, 08:01 PM
Thanks for your reply....

how can i make it to work as the values come from database and i cant assign different names. Do i need to use a for loop for it ?

felgall
03-09-2012, 08:54 PM
Set up a loop counter on the loop reading them in, increment the counter each time around the loop and add the current count to the end of the id so that each will be slightly different.

You'll then need to pass the value of the id into the JavaScript function so it knows which id to update.

addyking
03-09-2012, 08:59 PM
Can u give an example please......it kinda went like over my head :)

felgall
03-09-2012, 09:10 PM
<?php

include("../connection/conn.php");



?>
<script type="text/javascript">
function notEmpty(id){
var myTextField = document.getElementById(id);
document.getElementById(id).innerHTML = myTextField;

if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
}
</script>

</head>

<body>
<?php
$count = 1;
$sql=mysql_query("select * from menuscript");

while($row=mysql_fetch_array($sql))
{

?>

<div class="mine">
<?php echo $row['author'];?>


<form>
<input type='text' id='myText<?php echo $count ?>' />
<input type='button' onclick="notEmpty('mytext<?php echo $count ?>' );" value='Form Checker' /> </form>

</div>

<?php
$count++;
}?>

addyking
03-09-2012, 09:29 PM
thanks mann! that was really great!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum