从下拉列表中获取值并在Javascript中将结果显示在同一页面中

时间:2013-02-26 07:02:37

标签: javascript drop-down-menu calculator

这是标题。 它将结果显示在新页面中,而我想在运行代码的同一页面中显示结果。请帮助。

function calculate() {
    var width = document.getElementById("width");
    width1 =  width.options[width.selectedIndex].text;  
    var height = document.getElementById("height");
    var height1 =  height.options[height.selectedIndex].text;    
    var calculate = width1 * height1 * 3;
    result.innerHTML = "<div>" + calculate + "</div>";
}

Choose Width
<select id="width" name="height" onchange="calculate()">
    <option>1</option>
    <option>1</option>
</select>
<br/>
Choose Heiht
<select id="height" name="height" onchange="calculate()">
    <option>1</option>
    <option>2</option>      
</select>

2 个答案:

答案 0 :(得分:1)

您可以使用:

Choose Width:

<select id="width" name="height" onchange="calculate()">
    <option>1</option>
    <option>2</option>
</select>

    <br/>

   Choose Height

<select id="height" name="height" onchange="calculate()">
    <option>1</option>
    <option>2</option>      
</select>
<div id="result"></div>

和javascript应该是:

function calculate()
{
    var width = document.getElementById("width");
    width1 =  width.options[width.selectedIndex].text;  
    var height = document.getElementById("height");
    var height1 =  height.options[height.selectedIndex].text;    
    var calculate = width1*height1*3;
    var result = document.getElementById("result");
    result.innerHTML = calculate;
}

答案 1 :(得分:0)

您应该在HTML代码中将result作为div,然后您需要使用innerHTML或innerText来放置结果
添加新标记(在HTML代码中)

<div id="result"></div>

现在在JS中更新这个div元素

var result = document.getElementById("result");
result.innerText = calculate;