我这里有这个工作代码:
function updatetotal (section, pricetoadd)
{
TotalPrice[section] = pricetoadd;
total = 0;
for(key in TotalPrice)
{
total = total + TotalPrice[key];
}
$("#monthlycost").html("$" + total);
$("#firstpayment").html("$" + total);
}
<input {if $hw_s.disk[$_var].content == $__val.content}checked{/if} type=radio name="order[disk][{$_var}][content]" value="{$__val.content}" price="{$__val.price}" setup="{$__val.setup}" onclick="updatetotal('disk{$_var}', {$__val.price})">
请注意,该值非常重要。它必须是 $__val.content 才能使所有后端代码正常运行。
我想做的是将上面的内容转换为下拉菜单,并使功能仍然正常工作。 JS 函数保留每个选定项目的运行总计并将它们加在一起。对于输入类型的 radio 来说,这非常简单,因为 JS 函数可以接受价格变量。不幸的是,对于下拉菜单(据我所知), onChange 函数必须与选择相关联,而不是与选项相关联。不幸的是,由于选项是动态生成的,因此选择不知道有关选项的任何信息。
到目前为止的代码(不起作用):
function updatetotaldd(section, elementid)
{
var selectBox = document.getElementById(elementid);
var selectedValue = selectBox.options[selectBox.selectedIndex].value; // does not get what I need since value is a string. I need to somehow access the price of the selected option.
TotalPrice[section] = selectedValue;
for(key in TotalPrice)
{
total = total + TotalPrice[key];
}
$("#monthlycost").html("$" + total);
$("#firstpayment").html("$" + total);
}
<select class="tech" name="order[disk][{$_var}][content]" id="svtech{$_var+1}" data-enablecheckbox="false" onChange="updatetotaldd('disk{$_var}', 'svtech{$_var+1}')">
{foreach key=__var item=__val from=$_val}
<option {if $hw_s.disk.content == $__val.content}selected{/if} value="{$__val.content}" price="{$__val.price}" setup="${$__val.setup}" onSelect="updatetotaldd('disk{$_var}', 'svtech{$_var+1}')">
{$__val.content}
{if $__val.price > 0 && $__val.setup > 0}
<strong> - add ${$__val.price}/Mo + ${$__val.setup} One time fee</strong>
{elseif $__val.price > 0}
<strong> - add ${$__val.price}/Mo</strong>
{elseif $__val.setup > 0}
<strong>- add ${$__val.setup} One time fee</strong>
{/if}
</option>
{/foreach}
</select>
我怎样才能将价格传递给javascript(无论是选择上的onChange,还是选项本身的其他操作),或者以某种方式让选项具有可变属性(非值)?
最佳答案
fetch 是对的,我更正了错误。请参阅here .
var selectedOption = selectBox.options[selectBox.selectedIndex]; //need to somehow access the price of the selected option.
price= parseInt(selectedOption.getAttribute('price'));
关于javascript - HTML Select/Option 将值传递给 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16929828/