Basically, I am doing this: I have already read the database and obtained all the items, each includes a 'name' and a 'link'. On the page, I have an image, a select menu, and a button; each select option displays an item name (but no link information). I want to implement this: first select an option (nothing happen), and then click the button to change the image src to the selected item's link (in PHP variable). But I have trouble to pass the link to the javascript function, because it involves PHP variable. The code is like this:

<script type="text/javascript">
function selectItem(i) {
var name, link;
/*
...
*/
document.getElementById("name").innerHTML = name;
document.getElementById("pic").src = link;
}
</script>
...
<body>
<img id="pic" src="default.png">
<div id="name"></div>
<div onclick="location.href='javascript:selectItem(document.
    getElementsByName(&quot;menu&quot;)[0].value)';"></div>
<select name="menu">
    <option value="">select one</option>
    <?php
    $i = 0;
    foreach ($items as $item):
        echo ("<option value=\"" . $i . "\">" . $item['name'] . "</option>");
        $i++;
    endforeach;
    ?>
</select>
</body>

Thanks for helping!

link|improve this question

74% accept rate
feedback

2 Answers

Is the foreach loop actually looping? Try:

 <?php
$i = 0;
foreach ($items as $item) { ?>
    <option value="<? echo $i ?>"><? echo $item['name'] ?></option>
<?  $i++; }
?>
link|improve this answer
it is. But the problem is, I could only record the name here, not both name and link. – xuc Nov 3 '11 at 22:27
So you want the image to change after selecting the name of a different image and clicking the button? Where is your button? Are you using that div? Is there a reason you don't want to add the button to your form instead? – sdo Nov 3 '11 at 22:41
feedback
up vote 0 down vote accepted

I know this is late, but my solution is: to record name and link together (separated by " | ") in the attribute "value" of each option. Then there is no need to pass PHP variable to the JavaScript.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.