I'm add multilingual functionality to my page and having trouble with a select box. I want to change the language dynamically displayed on a page to match the chosen language in the select box.
This is my html code:
<?php
include_once 'multilingual_common.php';
?>
<!DOCTYPE>
<html>
<head>
<title>Test Form</title>
</head>
<body>
<div id="languages">
<select onChange="if (this.value) window.location.href=this.value">
<option value="multilingual_test.html?lang=en">English</option>
<option value="multilingual_test.html?lang=ko">한국어</option>
</select>
<a href="multilingual_test.html?lang=en">English</a>
<a href="multilingual_test.html?lang=ko">한국어</a>
</div>
<ul>
<li><?php echo $lang['CHARACTER_NAME']; ?> Rose</li>
<li><?php echo $lang['CHARACTER_LEVEL']; ?> 40</li>
<li><?php echo $lang['CHARACTER_SEX']; ?> female</li>
<li><?php echo $lang['CHARACTER_SEX']; ?> none</li>
</ul>
</body>
</html>
It works when clicking the tag but not the select box. The onChange event used in tag doesn't work. How should I fix this?
You are using a select list. Getting the value is a tad more complex.
A select list has many options
. The options are an array under the this
object in the onchange
event.
The current selected index is stored in this.selectedIndex
So to get a value, you need to acces the correct option in the array by the selected value
this.options[this.selectedIndex].value
is how you get a value from a select list.
To fix your code you should use instead of
<select onChange="if (this.value) window.location.href=this.value">
you need to get the value of the option
<select onChange="if (this.options[this.selectedIndex].value) window.location.href=this.options[this.selectedIndex].value">