基本上我有一个select menu
,他们可以在那里选择他们想要的座位,这些菜单有与之相关的定价值。eg value="100".
但现在我需要将座位的名称(Balcony,levelOne,levelTwo,lowerArea)打印到显示在html p
标签中的字符串中。
这是我的html:
<div data-role="fieldcontain">
<label for="selectmenu" class="select">Preferred Seating:</label> <!-- Following drop down checkbox -->
<select name="selectmenu" id="selectmenu">
<option name="selectmenu" value="200" id="lowerArea" >Lower Area($200)</option>
<option name="selectmenu" value="150" selected="selected" id="levelOne">Level 1($150)</option>
<option name="selectmenu" value="100" id="levelTwo">Level 2($100)</option>
<option name="selectmenu" value="200" id="balcony">Balcony($200)</option>
</select>
</div>
下面是javascript,还有其他值目前在不同的页面上。基本上,成本变量会获取所选的元素,并将其乘以他们输入的票证数量。我要做的是显示OrderInput+=()中的座位(阳台、下层区域等)seating变量。
cost = parseInt(document.getElementById('selectmenu').value,10) * numTickets;//This calculates the cost(selectMenu*numTickets)
var Orderemail = document.getElementById('txtOrderEmail').value;//This will grab the email value Inputed.
OrderInput +=("Your details are: <br />" + "Your E-mail address is: " + Orderemail + "<br />" + newsletter + "<br /> <br />" +
"You have the following tickets reserved: <br />" + numTickets +" on " + prefNight + " and your seating is :" + seating + "<br /> <br />" + "The total cost of your order will be: $" + cost);
document.getElementById('OrderInput').innerHTML = OrderInput;//This prints the users details to a html element.
document.getElementById('orderErrorMsg').innerHTML = '';//Removes error messages when everything is correct.
}
我想做的事情的简要介绍:我想打印orderInput变量中座位的座位安排名称。我只是不知道怎么做,因为它已经有价值了。它的价值很有价值,因为我需要它来获得座位的价格。谢谢
简单的方法是只split
innerText:
var seating=document.getElementById('selectmenu').innerText.split("(")[0];
更好的方法是从预构建数组中构建您的选择并使用ID。当用户选择某个内容时,您将搜索ID:
var array=[{name:"Lower Area",price:100},{name:"Level 1",price:150}];
var select=document.getElementById('selectmenu');
for(var id=0;id<array.length;id++) {
select.innerHtml+="<select value='"+id+"'>"+array[id].name+" ($"+array[id].value+")</select>";
}
//on change event:
var slectedId=document.getElementById('selectmenu').value;
var seating =array[slectedId].name;
var cost=array[slectedId].price*amount;
为什么上一个版本更好?你可以更容易地扩展它。想象一下,你必须增加折扣。在你目前的解决方案中,你需要进行第三次拆分,这会变得非常混乱。如果你使用一个数组,你可以很容易地扩展这个数组,并使用id array[selectedId].discount
请求值,然后计算总价。
编辑以便于理解
如果您有以下html:
<select name="selectmenu" id="selectmenu">
<option value="0">Lower Area ($200)</option>
<option value="1">Level 1 ($150)</option>
</select>
和Javascript数组:
var array=[{name:"Lower Area",price:100},{name:"Level 1",price:150}];
您可以通过更改事件上option
html标记的value
属性访问这些值:
document.getElementById('selectmenu').addEventListener("onchange",function() {
var slectedId=document.getElementById('selectmenu').value;
var seating =array[slectedId].name;
var cost=array[slectedId].price*amount;
});
为什么?因为这个:
var array=[{name:"Lower Area",price:100},{name:"Level 1",price:150}];
等于:
var array=[];
array[0]={name:"Lower Area",price:100};
array[1]={name:"Level 1",price:150};