我无法在JavaScript中显示select的值


I fail to display the value of a select in JavaScript

我有一个国家列表。我使用GeoNames的函数来检测我们所在的国家并将其显示在列表中。它的工作原理。然而,我想检索这个值,我试图显示它,但只有第一个值出现。代码:

<!-- 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);

为了演示,我对你的代码做了一点改动。

要做到这一点的方法是在Select上设置OnChange事件。如果您选择了一个选项,它将触发该事件。

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>

编辑:只需在你的身体中添加以下内容。onload例程:

setDefaultCountry ();

Greetz:)