Javascript:从下拉列表中选择值

时间:2013-09-26 09:12:11

标签: javascript

我有一个标准的计算javascript,现在我需要根据用户选择的值添加多个计算 - 似乎无法让它工作....!有人可以看看,告诉我哪里出错了?

<script type="text/javascript">
function calculate() {
  var noPeople = document.ContactForm.noPeople.value;
  var ddl = document.getElementById("menuType");
  var selectedValue = ddl.options[ddl.selectedIndex].value;
  var noPeople_excess = (noPeople-6);

  if (selectedValue == 3)  {
    var basic = 337;
    var marchCost = (50*noPeople);
    if (marchCost <= basic)         {
      document.ContactForm.marchCost.value = 337;
      document.ContactForm.marchCostVin.value = basic +(noPeople*25)
    } else {
      document.ContactForm.marchCost.value = basic +(noPeople_excess*34);
      document.ContactForm.marchCostVin.value = basic +(noPeople_excess*34)+(noPeople*25)
    }
  } else (selectedValue == 4)  {
    var basic = 368;
    var marchCost = (55*noPeople);
    if (marchCost <= basic) {
      document.ContactForm.marchCost.value = 368;
      document.ContactForm.marchCostVin.value = basic +(noPeople*25)
    } else {
      document.ContactForm.marchCost.value = basic +(noPeople_excess*44);
      document.ContactForm.marchCostVin.value = basic +(noPeople_excess*44)+(noPeople*25)
    }
  } else (selectedValue == 5) {
    var basic = 419;
    var marchCost = (60*noPeople);
    if (marchCost <= basic) {
      document.ContactForm.marchCost.value = 419;
      document.ContactForm.marchCostVin.value = basic +(noPeople*25)
    } else {
      document.ContactForm.marchCost.value = basic +(noPeople_excess*54);
      document.ContactForm.marchCostVin.value = basic +(noPeople_excess*54)+(noPeople*25)
    }
  }
}
</script>

3 个答案:

答案 0 :(得分:1)

这个问题的确经过多次回答,但这里有一个简单的解决方案:

    //get select value and assing to an input element
function setValue(selectId, elemId) {
    var thisID = selectId, 
    valueSelected = document.getElementById(thisID).value
    console.log(thisID + ' has value of ' + valueSelected);
    document.getElementById(elemId).value = valueSelected;
}

http://plnkr.co/edit/rnenKVaNcJ9RhqLzUaWi

问候。

答案 1 :(得分:0)

我可能会对这两个DDL感到困惑,但是所选的值应该是selectedIndex以与整数进行比较:

var selectedValue = ddl.selectedIndex;

或条件应该是检查字符串:

if (selectedValue == "3"){ 

答案 2 :(得分:0)

你的elses缺少if ..例如:else if(selectedvalue == 4)

我建议使用switch(selectedvalue){case 3:... break;案例4:......等 在这种情况下会更容易阅读,特别是如果您添加更多选项。