【发布时间】:2018-06-18 12:09:58
【问题描述】:
I have a form with a select element, radio buttons and checkboxes giving different options that, when selected/unselected, change the text inside the div underneath the form, automatically, using an onchange or oninput event.
这一切都适用于单选按钮和复选框,但不适用于 select 元素,我从页面加载时选择的选项中获取结果,一旦我将其更改为另一个选项,而不是我选择的选项改变了,它只会在我第一次对选择元素应用更改时改变结果。
注意:我试图只使用 JavaScript 而不使用 JQuery。
var form = document.pcform;
var optionIndex = form.elements.dropdown.options.selectedIndex;
var thrPrice = 250;
var fftPrice = 300;
var svtPrice = 350;
var i3Price = 100;
var i5Price = 290;
var i7Price = 450;
var dvdPrice = 190;
var blurayPrice = 250;
function totalPrice() {
var pcPrice = 0;
if (optionIndex == 0) {
pcPrice = pcPrice + thrPrice;
}
if (optionIndex == 1) {
pcPrice = pcPrice + fftPrice;
}
if (optionIndex == 2) {
pcPrice = pcPrice + svtPrice;
}
if (document.getElementById('i3').checked) {
pcPrice = pcPrice + i3Price;
}
if (document.getElementById('i5').checked) {
pcPrice = pcPrice + i5Price;
}
if (document.getElementById('i7').checked) {
pcPrice = pcPrice + i7Price;
}
if (document.getElementById('dvd').checked) {
pcPrice = pcPrice + dvdPrice;
}
if (document.getElementById('bluray').checked) {
pcPrice = pcPrice + blurayPrice;
}
document.getElementById('priceDiv').innerHTML = "Your computer costs USD" + pcPrice;
}
pcform.addEventListener("change", totalPrice);
<form action="" name="pcform">
<p>
Get the computer exactly how you want it!
</p>
<label for=screens> Screen size: </label>
<select id="dropdown" onchange="totalPrice()">
<option id="thrteen" value="thirteen">13"</option>
<option id="ffteen" value="fifteen">15"</option>
<option id="svteen" value="seventeenthree">17,3"</option>
</select>
<p>Select the processor: <br />
<label for="i3">
<input type="radio" value="corei3" id="i3" name="processor">
Core i3
</label>
<label for="i5">
<input type="radio" value="corei5" id="i5" name="processor">
Core i5
</label>
<label for="i7">
<input type="radio" value="corei7" id="i7" name="processor">
Core i7
</label>
</p>
<p>Components: <br/>
<label for="dvd"><input type="checkbox" value"dvdrom" id="dvd">
DVD-ROM
</label>
<label for="bluray"><input type="checkbox" value="bluray" id="bluray">
Blu bluray
</label>
</form>.
<div id="priceDiv"></div>
【问题讨论】:
-
你在 onselect 之前设置了选项索引并且从不更新它
标签: javascript html forms