I have a list of countries. I use the GeoNames's function for detect the country where we are and display it in the list. It works. However, I'd like to retrieve this value, I try to display it but only the first value appears. Code :
<!-- Code HTML countries list -->
<select id="countrySelect" name="country">
<?php
$reponse = $bdd->query('SELECT * FROM pays');
echo '<OPTION VALUE="">Pays</OPTION>';
while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC))
{
echo '<OPTION VALUE="'.$donnees["id_pays"].'">'.$donnees["pays"].'</OPTION>';
echo $donnees["pays"];
}
?>
Code Javascript :
function setDefaultCountry() {
var countrySelect = document.getElementById("countrySelect");
for (i=0;i< countrySelect.length;i++) {
if (countrySelect[i].value == geonamesUserIpCountryCode) {
countrySelect.selectedIndex = i;
}
}
}
/* I want to display the country selected here !!!!!!*/
var c = document.getElementById("countrySelect");
alert(c.options[c.selectedIndex].text);
i made a little change to your code, for demonstration purposes.
The way to do it is to set an OnChange Event on the Select. If you then choose an option, it will fire the event.
function setDefaultCountry() {
var countrySelect = document.getElementById("countrySelect");
for (i = 0; i < countrySelect.length; i++) {
if (countrySelect[i].value == geonamesUserIpCountryCode) {
countrySelect.selectedIndex = i;
}
}
check();
}
function check() {
var sele = document.getElementById("countrySelect");
alert(sele[sele.selectedIndex].text);
}
<!-- Code HTML countries list -->
<select id="countrySelect" name="country" onchange="check()">
<OPTION VALUE="Test1">test1</OPTION>
<OPTION VALUE="Test2">test2</OPTION>
<OPTION VALUE="Test3">test3</OPTION>
<OPTION VALUE="Test4">test4</OPTION>
<OPTION VALUE="Test5">test5</OPTION>
EDIT: just add the following in your body.onload routine: setDefaultCountry();
Greetz :)