2014-01-18 148 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>