/* need to populate cost dynamically from a selection ex radio button */
function calculateCost() {
var scoop_prices = new Array();
scoop_prices["single"] = 8;
scoop_prices["double"] = 14;
var scoopCost = 0;
var theForm = document.forms["iceCreamForm"];
var selectedScoop = theForm.elements["typeOfScoop"];
for(var i = 0; i < selectedScoop.length; i++)
{
if(selectedScoop[i].checked) {
scoopCost= scoop_prices[selectedScoop[i].value];
break;
}
}
return scoopCost;
/* issue from here */
var s3 = document.getElementById("scoopy");
s3.innerHTML = s3.innerHTML + "Approx xost in $" + scoopCost;
/* i guess dom is not yet loaded to print the above statement , help me to fix this */
}
<div class="choose" id="choosen">
<form action="" id="iceCreamForm" onsubmit="false;">
<label>choose the scoop you want</label><br />
<input type="radio" id="s1" name="typeOfScoop" value="single" onclick="calculateCost()" />single
<input type="radio" id="s2" name="typeOfScoop" value="double" onclick="calculateCost()" />double<br />
</form>
</div>
<!--want to display the ouput on selection of any radio buttons above -->
<div id="scoopy"> </div><br />
和许多单选按钮或其他多个选择按钮后跟
答案 0 :(得分:0)
如果我理解正确,问题是您尝试将html放在return
语句之后。好吧,一旦你致电return
,下面的代码永远不会执行,所以,将此代码移到return
语句之上。
在函数中调用return语句时,将停止执行此函数
<子> https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/return#Description 子>
注意:如果您只是需要显示html,则不需要使用return
。只有当你期望从函数中得到结果时才需要它。
/* need to populate cost dynamically from a selection ex radio button */
function calculateCost() {
var scoop_prices = new Array();
scoop_prices["single"] = 8;
scoop_prices["double"] = 14;
var scoopCost = 0;
var theForm = document.forms["iceCreamForm"];
var selectedScoop = theForm.elements["typeOfScoop"];
for(var i = 0; i < selectedScoop.length; i++)
{
if(selectedScoop[i].checked) {
scoopCost = scoop_prices[selectedScoop[i].value];
break;
}
}
var s3 = document.getElementById("scoopy");
s3.innerHTML = "Approx xost in $" + scoopCost;
// you don't need it
// return scoopCost;
}
&#13;
<div class="choose" id="choosen">
<form action="" id="iceCreamForm" onsubmit="false;">
<label>choose the scoop you want</label><br />
<input type="radio" id="s1" name="typeOfScoop" value="single" onclick="calculateCost()" />single
<input type="radio" id="s2" name="typeOfScoop" value="double" onclick="calculateCost()" />double<br />
</form>
</div>
<!--want to display the ouput on selection of any radio buttons above -->
<div id="scoopy"> </div><br />
&#13;
答案 1 :(得分:0)
如果您在点击单选按钮时传递value(price)
,则可以使用最少的代码行来实现此目的
<强> HTML 强>
将scoop的价格作为单选按钮的值。 onclick
将此值传递给处理函数。另请注意,input
没有结束标记。你不需要</input>
。相反,输入应使用标签
<input type="radio" id="s1" name="typeOfScoop" value="8" onclick="calculateCost(this.value)" >single
<input type="radio" id="s2" name="typeOfScoop" value="14" onclick="calculateCost(this.value)">double
<强> JS 强>
onclick
将值传递给处理函数&amp;更新DOM
function calculateCost(price) {
var s3=document.getElementById("scoopy");
s3.innerHTML= "Approx xost in $" + price;
}