doupaoyan6083 2015-05-29 13:03
浏览 33
已采纳

我无法在JavaScript中显示select的值

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);
  • 写回答

1条回答 默认 最新

  • douxi3404 2015-05-29 13:16
    关注

    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 :)

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多