在 JavaScript 中將下拉列表(選擇器)的所選值顯示在控制檯上?


假設以下是我們下拉列表(選擇器)−

<select onchange="selectedSubjectName()" id="subjectName">
   <option>Javascript</option>
   <option>MySQL</option>
   <option>MongoDB</option>
   <option>Java</option>
</select>

以下程式碼可在控制檯上顯示所選值 −

範例

 即時演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<select onchange="selectedSubjectName()" id="subjectName">
<option>Javascript</option>
<option>MySQL</option>
<option>MongoDB</option>
<option>Java</option>
</select>
<script>
   function selectedSubjectName() {
      var subjectIdNode = document.getElementById('subjectName');
      var value =
      subjectIdNode.options[subjectIdNode.selectedIndex].text;
      console.log("The selected value=" + value);
   }
</script>
</body>
</html>

若要執行上述程式,請儲存檔名“anyName.html(index.html)”,然後右擊該檔案。在 VS 程式碼編輯器中選擇“使用 Live Server 開啟”選項。

輸出

這將生成以下輸出 −

現在,我將選擇 Java。快照如下 −

之後,我將選擇 MongoDB。快照如下 −

更新於: 2020 年 9 月 14 日

3 千次以上瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.