如何让警报框显示下拉选项的总数?

时间:2012-02-29 19:20:55

标签: javascript jquery

我在此脚本中出错并且警告框不计算总数,有人可以帮忙吗? 警告框只显示0但我需要它来总计2个下拉选项的值

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #fff; }
</style>
</head>
<body>
<select id="t_dermal_name">
<option value="t_default_dermal">-- Choose --</option>
<option value="1" rel="30">Between Eyebrows</option>
<option value="7" rel="30">Individual Line Softening</option>
<option value="2" rel="30">Lip Contouring</option>
</select>
<select id="t_wrinkle_name">
<option value="t_default_wrinkle">-- Choose --</option>
<option value="1" rel="30">Between Eyebrows</option>
<option value="7" rel="30">Individual Line Softening</option>
<option value="2" rel="30">Lip Contouring</option>
</select>
<br />
<button id="btn1">click</button>
<script>
 $(document).ready ( function () {
    $("#btn1").click ( function () {
      var resultVal = 0.0;
      var objRegExp = '\s+';
       $(".test").each ( function() {
            resultVal += parseFloat ( $(this).val().replace(/\s /g,'').replace(',','.'));
        });
        alert ( resultVal );  
    });
});

</script>
<script src="/js/render/edit.js"></script>
<script>var _gaq=[['_setAccount','UA-1656750-13'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)})(document,'script')</script></body>

</html>

2 个答案:

答案 0 :(得分:2)

$(".test").each
不知道这是否是你唯一的问题,但是...你没有类test的任何元素,所以你的代码什么也没做,因为选择器什么都没有,所以你留在0

也许你的意思是:

$("select").each (function() { ... // Will select all the select elements.

您还可以使用以下方法简化代码:

$("#btn1").click (function () {
    var resultVal = 0;
    $("select").each(function() {
        resultVal += parseFloat($(this).val());
    });
    alert (resultVal);  
});

答案 1 :(得分:1)

$("#btn1").click ( function () {
    var total = 0;

    $('select[id*="_name"]').each(function(){
        total += parseFloat($(this).val());
    });

    alert(total);
});