Web Hosting Talk







View Full Version : Javascript with PHP / HTML - Idiot Question


MikeUK
01-15-2009, 08:39 AM
Hi all
I'm fairly comfortable with PHP, but I'm having a (probably very simple) issue with a javascript event handler function. I've had it before but got round it other ways.
I don't think this is an issue with any particular piece of code, more about a basic gap in my knowledge. I suspect this will be a 2 second solution for someone more js experienced than me.
Here's an example:
(...part of a php file...)
?><form name="selectionformname" id="selectionformid"><?php
foreach($selections as $selection) { ?>
<div>
<label for="<?php echo $selection ?>"><?php echo $selection ?></label>:
</div>
<select id="selectboxid" name="selectboxname" MULTIPLE SIZE=4 onchange="dofunc()">
<?php foreach ( $option as $option_item ) : ?>
<option id="optionid" name="optionname" value="<?php echo $option_item ?>"><?php echo $options_item ?></option>
<?php endforeach; ?>
</select>
<?php } ?>
</form>
<textarea width="300px" rows="5" name="textareaname" id="textareaid">
</textarea>
<script language="javascript" type="text/javascript">
function dofunc() {
document.getElementById('textareaid').value=document.selectformname.selectboxname.optionname.value;
}
</script>
When running this, clicking on an option leads to this error in the Firefox error console:
"Error: document.selectformname is undefined"
Clearly this is me not knowing something about how the DOM works. I've put the js script in different places within the file with no change.
I wonder if it is something to do with it being a php file within a chain of other php files? Hence this file has no <head> / <body> tages (which all the internet examples use).
Anyone able to assist? Thanks in advance.

Xeentech
01-15-2009, 09:08 AM
The <form> has name="selectionformname", but in script you're using document.selectformname. Simple typo? Or was this not actually your full code, and a mock up for us to work?
Working with DOM and forms based on name="" is a mantaince nightmare (IMO).
Why not,
<select onchange="dofunc(this.value);">
and pass the value of the changed <select> element to the function?

MikeUK
01-15-2009, 09:25 AM
That was a typo, and yes it is a mock up (because the original code is surrounded by a lot of other php stuff that would've made this post twice as long), so the undefined error wasn't due to that (but well spotted - should have seen that as I was pretty careful with this code).
Your idea sounds much better. Will give that a go. Thanks!

MikeUK
01-15-2009, 05:31 PM
Xeentech, thank you, that worked much better.