iT邦幫忙

0

jquery value of select 相加總共?

$('#s_all,#s_half,#s_cut').change(function(){   
var s_sum = 0; 
    $('#s_all option:selected,#s_half option:selected,#s_cut option:selected').each(function() {
        s_sum += Number($(this).val());
    });
     $("#s_sum").html(s_sum);
  var s_total = s_sum * 620;
  $("#s_total").html(s_total);
});

$('#hs_all,#hs_cut').change(function(){   
var hs_sum = 0;   
    $('#hs_all option:selected,#hs_cut option:selected').each(function() {
        hs_sum += Number($(this).val());
    });
     $("#hs_sum").html(hs_sum);
  var hs_total = hs_sum * 310;
  $("#hs_total").html(hs_total);
});

請問...我要如何把s_total跟hs_total相加?
假設加入這段

var total = s_total+hs_total;
$("#total").html(total);

他都會出現 [object HTMLSpanElement] 訊息

看更多先前的討論...收起先前的討論...
jerry00218 iT邦好手 10 級 ‧ 2016-10-06 00:24:52 檢舉
$("#total").val(total); ??
fillano iT邦超人 1 級 ‧ 2016-10-06 08:46:02 檢舉
注意一下scope,改一下變數宣告的位置。
火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 11:27:47 檢舉
甚麼是scope?
火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 11:42:04 檢舉
jerry00218 不行 ><
火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 11:42:37 檢舉
如果我把 var s_sum = 0; 放在function外面 就會不對.....
fillano iT邦超人 1 級 ‧ 2016-10-06 17:32:50 檢舉
你需要相加的變數是什麼?好像不是s_sum吧XD
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
糖炒栗子
iT邦新手 5 級 ‧ 2016-10-06 11:58:06
最佳解答

建議設定一個CLASS

$('#s_all,#s_half,#s_cut,#hs_all,#hs_cut').change(function(){ 
    $("#total").html($("#hs_total").val() + $("#s_total").val());
});
看更多先前的回應...收起先前的回應...

.val() 要是 input, select and textarea才能用

火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 12:07:32 檢舉

我這樣做後數字不對 後面會多很多0

$('#s_all,#s_half,#s_cut,#hs_all,#hs_cut').change(function(){ 
    $("#total").html(
    $("#s_all").val() + $("#s_half").val() +
    $("#s_cut").val() * 620 + 
    $("#hs_all").val() + $("#hs_cut").val() * 310
    );
});

怎麼會這樣?

火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 12:09:43 檢舉

我用了你的方法後他沒有出現加總的結果~~
我的是select

火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 13:50:31 檢舉

多了一個問題...
當使用者下一步後想回去改東西
上一頁時,欄位值還在 但是juqery沒有作用...如何讓他再度執行一次?當回到上一頁後?

<script>
    $(function(){
        var sel1_val=0,sel2_val=0;
        $('select[name=sel_1]').change(function(){
            sel1_val = $('select[name=sel_1] > option:selected').val() * 10;
            calc();
        });
        $('select[name=sel_2]').change(function(){
            sel2_val = $('select[name=sel_2] > option:selected').val() * 20;
            calc();
        });
        function calc() {
            $('#total').val(sel1_val+sel2_val);
        }
    })
</script>
<body>
    <select class="" name="sel_1">
        <option value="10">10</option>
        <option value="20">20</option>
    </select>

    <select class="" name="sel_2">
        <option value="30">30</option>
        <option value="40">40</option>
    </select>

    <input type="text" val="0" id="total" />
</body>

第二個問題
看你jq要做什麼啊
你jq是觸發事件的話 就要再次觸發

火爆浪子 iT邦研究生 1 級 ‧ 2016-10-06 14:40:47 檢舉

好的~ 是要在body寫嗎 那這樣要怎麼寫才對?

你可以把code貼到https://jsfiddle.net/
再分享出來

我要發表回答

立即登入回答