简体   繁体   中英

How can I get the alert box to show total from dropdown selections?

I've made an error in this script and the alert box doesn't calculate the total, can anyone help please? The alert box just shows 0 but I need it to total the value of the 2 dropdown selections

<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>

$(".test").each
Don't know if this is your only problem but... You don't have any elements with the class test so your code does nothing as the selector grabs nothing, so you stay with 0 .

Maybe you meant:

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

You can also simplify the code with:

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

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

    alert(total);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM