[英]Using Javascript to select a value from a Html Select box
大家好,我使用JavaScript從html select form標記中選擇一個特定的值(選項),但是每當我調用JavaScript函數時,都會收到一條消息,重復我要選擇的所有選項。 例如:如果我選擇從選項列表中選擇“兔子”,然后顯示一條消息“選擇了兔子”; 該消息將針對所選的每個選項/值顯示。
這是我的JavaScript代碼:
var element = document.getElementById('choices').value;
function SelectElement() {
if (element = 'Rabbit') {
alert("Rabbit Selected");
}
else if (element = 'Wall') {
alert("Wall Selected");
}
else if (element = 'Arrow') {
alert("Arrow Selected");
}
}
這是我的html代碼:
<form>
<select id="choices" >
<option>Rabbit</option>
<option>Wall</option>
<option>Arrow</option>
</select>
<input type="button" value="Submit" onclick="SelectElement()"/>
</form>
你們聰明人可以幫我嗎????
答:您應該在調用函數之前每次獲取值,然后檢查它,否則您的element
變量將根本不會刷新。
B.要比較兩個值,應使用==
, =
是賦值運算符。
function SelectElement() {
var element = document.getElementById('choices').value;
if (element == 'Rabbit') {
alert("Rabbit Selected");
}
}
(因為您的問題不太清楚),如果您只想為每個單擊的選項提醒選定的值,請執行以下操作:
function SelectElement() {
var element = document.getElementById('choices').value;
alert(element+" Selected");
}
這是基本的字符串連接。
在“選擇”標簽中有一個叫做selected == true
或false
的東西。
您可以用HTML編寫:
<form>
<select id="choices">
<option id="Rabbit">Rabbit</option>
<option id="Wall">Wall</option>
<option id="Arrow">Arrow</option>
</select>
</form>
<button onclick="TakeElement()">Click</button>
您可以用javascript編寫:
var ra = document.getElementById('Rabbit');
var wa = document.getElementById('Wall');
var ar = document.getElementById('Arrow');
function TakeElement() {
if (ra.selected == true) {
alert("Rabbit is selected");
}
if (wa.selected == true) {
alert("Wall is selected");
}
if (ar.selected == true) {
alert("Arrow is selected");
}
}
我認為您必須將element ='rabbit'
替換為element =='rabbit'
==
是比較運算符,而=
是賦值運算符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.