如何计算用户选择的两个下拉菜单的总值。我在HTML中没有预先确定的值。这是我的代码,我希望将门票数量乘以所选价格并将其显示给用户。感谢。
HTML
<select name="price" id="price" style="width:120px">
<option>Select Price</option>
</select>
<br>
<br>
<select name="tickets" id="tickets" style="width:120px">
<option>Select Tickets</option>
</select>
<br>
<br>
<input name="button" type="button" value="Submit" onClick="return validate2()"/>
<input name="reset" type="reset" value="Reset" />
</form>
的JavaScript
switch (artist.selectedIndex)
{
case 0:
var venueList = ["Select Venue"];
var dateList = ["Select Date"];
var ticketList = ["Select Tickets"];
var priceList = ["Select Price"];
fillList(venue, venueList);
fillList(date, dateList);
fillList(ticket, ticketList);
fillList(price, priceList);
break;
case 1:
var venueList = ["Select Venue", "London"];
var dateList = ["Select Date", "17th July", "18th July"];
var ticketList = ["Select Tickets", "1", "2", "3", "4", "5", "6"];
var priceList = ["Select Price", "£30", "£45", "£70"];
fillList(venue, venueList);
fillList(date, dateList);
fillList(ticket, ticketList);
fillList(price, priceList);
break;
case 2:
var venueList = ["Select Venue", "Manchester", "Glasgow"];
var dateList = ["Select Date"]
var ticketList = ["Select Tickets", "1", "2", "3", "4", "5", "6"];
var priceList = ["Select Price", "£35", "£50", "£60"];
fillList(venue, venueList);
fillList(date, dateList);
fillList(ticket, ticketList);
fillList(price, priceList);
// adding onchange event on venue when the user selects rod stewart
venue.onchange = function ()
{
var dateList;
switch(venue.selectedIndex)
{
case 0: dateList = ["Select Date"]; break;
case 1: dateList = ["Select Date", "18th July", "20th July"]; break;
case 2: dateList = ["Select Date", "22nd July", "23rd July"]; break;
}
fillList(date, dateList);
}
break;
答案 0 :(得分:0)
首先,我假设场地,日期,门票和价格是对选择元素的引用。
但是根据您当前的代码,我建议使用类似的内容 -
function validate2() {
var truePrice = parseFloat(String.replace(price.options[price.selectedIndex].value, '£', '')),
noOfTickets = parseInt(ticket.options[ticket.selectedIndex].value);
return truePrice * noOfTickets;
}
http://fiddle.jshell.net/J4Ryy/3/根据我的回答,这是一个工作小提琴:)
答案 1 :(得分:0)
您必须将两个下拉列表的值输入变量。 您的下拉列表或其他hthml标记的值是一个字符串。
您必须将字符串转换为数字。 如何执行此操作,您可以在此处阅读:How do I convert a String into an integer
之后,您可以执行正常操作,例如
var c = var a + var b
Greethings
答案 2 :(得分:0)
使用jQuery:
<script src="https://code.jquery.com/jquery.js"></script>
<script>
$('select').on('change', function (e) {
var tickets = $('#tickets').val();
var price = $('#price').val().substring(1);
alert(tickets * price);
});
</script>
说明:每次选择框更改时,我们都会通过获取选择框的值来计算总价。 .substring(1)通过从位置1到结尾获取子字符串来删除井号。
您可以更改警报以执行其他操作,例如将其放入框中:
$('#resultBox').html(tickets * price);