2014-01-18 146 views
0

我測試了使用普通的HTML下拉菜單,當談到這個提交按鈕,我遇到了一個問題...的Javascript提交按鈕不起作用

以下是我的代碼:

<head> 
<script> 
function submitButton() 
{ 
var mylist=document.getElementById("myList"); 
document.getElementById("favorite").innerHTML=mylist.options[mylist.selectedIndex].text; 
} 
</script> 
</head> 

<body> 
<form> 
<select id="myList"> 
    <option> </option> 
    <option>A</option> 
    <option>B</option> 
    <option>C</option> 
    <option>D</option> 
</select> 
<button onclick= 'submitButton()'> Submit </button> 
<p>You chose: <span id= 'favorite'> </span></p> 
</form> 
</body> 

現在,當我在Adobe Dreamweaver中通過Live運行此代碼時,它的工作原理完全如我所願;當我從我的下拉菜單中選擇一些內容並按下提交按鈕時,特定的字母在'您選擇:'後出現。

但是,當我在谷歌瀏覽器和Safari中運行它時,結果會有所不同。當我從下拉列表中選擇,然後按'提交'時,該字母出現在一秒鐘內,然後該頁面似乎自動刷新,而下拉爲原始值,空白爲<span>。有誰知道爲什麼,我怎麼能解決這個問題呢?

+0

你應該使用舊學校的輸入類型。始終有效。 –

回答

1

默認情況下,表單中的<button>將提交加載表單的動作url或同一頁面的表單(如果沒有表單的話)。
只需將按鈕類型更改爲可防止提交表單的按鈕。

<button type="button" onclick= 'submitButton()'> Submit </button> 
+0

非常感謝 – JaredCubilla

1

你可以試試這個也

<head> 
<script> 
function submitButton() 
{ 
var mylist=document.getElementById("myList"); 
document.getElementById("favorite").innerHTML=mylist.options[mylist.selectedIndex].text; 
} 
</script> 
</head> 

<body> 
<form> 
<select id="myList"> 
    <option> </option> 
    <option>A</option> 
    <option>B</option> 
    <option>C</option> 
    <option>D</option> 
</select> 
<input type="button" onclick= 'submitButton()' value="Submit" /> 
<p>You chose: <span id= 'favorite'> </span></p> 
</form> 
</body>