使用javascript onchange并在表单内选择不起作用。如果放在表格外面就可以了

时间:2015-03-06 13:05:48

标签: javascript html forms select onchange

我正在创建一个实时显示更改的表单。当我将代码放在表单中时,它停止工作。

以下是HTML代码:

<form id="selectform" name="myform" action="dothis.php" method="post">
 <select id="selectProfileIcon" name="newentry" onchange="selectProfileIcon()">
    <option value="aboutme">ABOUT ME</option>
    <option value="aboutus">ABOUT US</option>
    <option value="alert">ALERT</option>
    <option value="services">SERVICES</option>
    <option value="deals">DEALS</option>
    <option value="events">EVENTS</option>
    <option value="hotdeals">HOT DEALS</option>
    <option value="hotpicks">MY PICKS</option>
    <option value="newitems">NEW ITEMS</option>
    <option value="onsale">ON SALE</option>
    <option value="promo">PROMOTION</option>
    <option value="recall">RECALL</option>
</select>
</form>
<br>
<br>
<br>
<div id="profileIcon">ABOUT ME</div>

这是Javascript

function selectProfileIcon() {
var ta = document.getElementById("selectProfileIcon");
var div = document.getElementById("profileIcon");
if (ta.value === "aboutme") {
    div.innerHTML = "ABOUT ME";
} else if (ta.value === "aboutus") {
    div.innerHTML = "ABOUT US";
} else if (ta.value === "alert") {
    div.innerHTML = "ALERT";
} else if (ta.value === "services") {
    div.innerHTML = "SERVICES";
} else if (ta.value === "deals") {
    div.innerHTML = "DEALS";
} else if (ta.value === "events") {
    div.innerHTML = "EVENTS";
} else if (ta.value === "hotdeals") {
    div.innerHTML = "HOT DEALS";
} else if (ta.value === "hotpicks") {
    div.innerHTML = "MY PICKS";
} else if (ta.value === "newitems") {
    div.innerHTML = "NEW ITEMS";
} else if (ta.value === "onsale") {
    div.innerHTML = "ON SALE";
} else if (ta.value === "promo") {
    div.innerHTML = "PROMOTION";
} else if (ta.value === "recall") {
    div.innerHTML = "RECALL";
} else {
    div.innerHTML = "No selection";
}
}

以下是jsfiddle:JSFIDDLE LINK

中的代码

尝试删除表单标记,它可以正常工作。把它放回去禁用它。

如果您有替代代码,那么最受欢迎。我真的很好奇为什么它在表格内部不起作用。谢谢!

1 个答案:

答案 0 :(得分:2)

问题不在于<form>,而在于您的元素ID与您的函数名称相同。重命名ID或功能。

<强> HTML

<select id="test" name="taurus" onchange="selectProfileIcon()">

<强>的JavaScript

function selectProfileIcon() {
    var ta = document.getElementById("test");
    // etc...
}

JSFiddle