如何根据选择的选项更改消息

时间:2015-09-25 10:27:30

标签: javascript options

所以我需要在用户选择一个选项时更改消息。我似乎无法改变消息。这就是我所拥有的。

HTML:

<p>
    <label for="primaryBill">Primary Bill: C# 000000</label>
</p>
<p>
    <label for="comparisonbill" style="border: 2px solid black;">Comparison Bill:</label>
    <select style="border: 2px solid black;" name="comp" id="comp">
        <option selected="selected" id="1" value="-100%">C# 123456</option>
        <option value="14.88%">C# 999999</option>
        <option value="-29.11">C# 987654</option>
    </select>
 </p>
 <p id="message"></p>

JS:

var a = document.getElementById("comp");
var b = a.options[a.selectedIndex].value;
var c = document.getElementById("1").value;
var function = changingMessage() {
if (b != c) {
            document.getElementById("message").innerHTML = "Usage has increased" + b + "year over year";
        }
        else { document..getElementById("message").innerHTML ="Usage has decreased" + c + "year over year";
        }
        }

1 个答案:

答案 0 :(得分:0)

更新你的功能

function changingMessage() {
var b = a.options[a.selectedIndex].value;
if (b != c) {
            document.getElementById("message").innerHTML = "Usage has increased" + b + "year over year";
        }
        else { document.getElementById("message").innerHTML ="Usage has decreased" + c + "year over year";
        }
    }

并在选择框

上添加onchange事件
<select style="border: 2px solid black;" name="comp" onchange="changingMessage()" id="comp">

检查此代码段

var a = document.getElementById("comp");

var c = document.getElementById("1").value;
function  changingMessage() { 
  var b = a.options[a.selectedIndex].value;
if (b != c) {
            document.getElementById("message").innerHTML = "Usage has increased" + b + "year over year";
        }
        else { document.getElementById("message").innerHTML ="Usage has decreased" + c + "year over year";
        }
}
<p>
    <label for="primaryBill">Primary Bill: C# 000000</label>
</p>
<p>
    <label for="comparisonbill" style="border: 2px solid black;">Comparison Bill:</label>
    <select style="border: 2px solid black;" name="comp" id="comp" onchange="changingMessage()">
        <option selected="selected" id="1" value="-100%">C# 123456</option>
        <option value="14.88%">C# 999999</option>
        <option value="-29.11">C# 987654</option>
    </select>
 </p>
 <p id="message"></p>