PDA

View Full Version : getElementById Script wont work when repeated



leetee4000
08-13-2008, 11:17 AM
I have the below javascript on my page that is intended to populate a text box until the user acticates it and then goes blank.

This code works on a page once, but I need this repeating muliple times within a PHP while loop. For some reason it will not work when it is on the page multiple times even though I have used $i variable so that each one has a unique element ID. Does anyoen have any ideas why this wont work?

Many thanks


<?
if(isset($_POST['qty'])){
$qty = $_POST['qty'];
} else {
$qty = 'qty';
}
?>
<script type="text/javascript">

window.onload=function(){

var inp<?=$i?>=document.getElementById('inp<?=$i?>'), // Set the input element's ID.

text='<?=$qty?>'; // Default input text's value. This should match on the value of your value attribute.

inp<?=$i?>.onfocus = function()

{this.style.color='#222';this.value=(this.value==text)?'':this.value;}

inp<?=$i?>.onblur= function()
{
if(this.value=='')
{
this.value=text;
this.style.color='#aaa';
}
else this.value;
}
}
</script>
<input type="text" name="colour" id="inp<?=$i?>" value="<?=$qty?>" class="contact" style="width:15px; height:14px; font-size:9px;color:#666;float:left;margin-top:2px">

jscheuer1
08-13-2008, 03:04 PM
There is only one window.onload per page. Each successive one that your PHP loop creates overwrites (in memory only) the previous one. So, the last one in the series would still work. If that's happening, here is another way of doing it without window.onload, that should work. Replace the part from your post with this:


<?
if(isset($_POST['qty'])){
$qty = $_POST['qty'];
} else {
$qty = 'qty';
}
?>
<input type="text" name="colour" id="inp<?=$i?>" value="<?=$qty?>" class="contact" style="width:15px; height:14px; font-size:9px;color:#666;float:left;margin-top:2px">
<script type="text/javascript" defer>

;(function(){

var inp<?=$i?>=document.getElementById('inp<?=$i?>'), // Set the input element's ID.

text='<?=$qty?>'; // Default input text's value. This should match on the value of your value attribute.

inp<?=$i?>.onfocus = function()

{this.style.color='#222';this.value=(this.value==text)?'':this.value;}

inp<?=$i?>.onblur= function()
{
if(this.value=='')
{
this.value=text;
this.style.color='#aaa';
}
else this.value;
}
})();
</script>

However, aside from the window.onload problem, the highlighted above looks wrong to me. It should perhaps be replaced by:


inp<?=$i?>.onblur= function()
{
if(this.value=='')
this.value=text;
this.style.color='#aaa';
};

or maybe:


inp<?=$i?>.onblur= function()
{
if(this.value==''){
this.value=text;
this.style.color='#aaa';
};
};

But if it works for you 'as is', I wouldn't worry about it too much. It's just that this line from your version:


else this.value;

doesn't look like it would do anything, and may even cause an error.