2016-04-25 38 views
-1

我在試圖構建一個jacvascript運行總計算器,它允許用戶指定被起訴的輸入來計算顯示在屏幕上的(總和)總和。javascript確認框if語句

在用戶對輸入進行更改之前,我想要一個確認框,允許用戶選擇好(這導致新的總數正在計算)或取消。

我已將帶有IF語句的確認框代碼插入到GetTotal函數中,但似乎沒有工作。無論用戶是選擇好還是取消,每次計算新總數。任何幫助不勝感激。邁克

<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.1/js/bootstrap-dialog.min.js"></script> 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> 
</head> 

<script> 
var input1 = 5555; 
var input2 = 666; 

$(document).ready(function() { 
    document.getElementById("input1").value = input1; 
    document.getElementById("input2").value = input2; 
    GetFirstTotal(); 
}); 

function GetFirstTotal() { 
    var total = 0; 
    $('input[type=text]').each(function(index, value) { 
     total += parseInt($(value).val() || 0); 
    }); 

    $("#chkTotal").html(total); 
} 

function GetTotal() { 
    var total = 0; 
BootstrapDialog.confirm('Are you sure you want to do this?'); 
if(confirm("text")==1) 
{ 
    $('input[type=text]').each(function(index, value) { 
     total += parseInt($(value).val() || 0); 
    }); 

    $("#chkTotal").html(total); 
} 
else {}} 
</script> 

TOTAL: 
<div id="chkTotal"></div> 
<br> 
<input type="text" name="input1" id="input1"/> 
<input type="button" value="Change X" onclick="GetTotal(this)"/> 
<br> 
<br> 
<input type="text" name="input2" id="input2"/> 
<input type="button" value="Change Y" onclick="GetTotal(this)"/> 
+1

我扔掉問我,如果你真的想要它做的工作任何計算器。 – kay

回答

1

默認的Javascript confirm()函數應返回一個布爾值,所以你應該只能夠使用:

if(confirm('Are you sure you want to do this?')) 
{ 
     // Do these things 
     $('input[type=text]').each(function(index, value) { 
      total += parseInt($(value).val() || 0); 
     }); 
     $("#chkTotal").html(total); 
} 

但是,看來,你正在使用的BootstrapDialog插件,其中似乎以不同的方式操作了一下,接受回調,檢查已輸入的值:

enter image description here

所以,你的代碼可能會是這個樣子,如果你想只使用它作爲一個選項確認:

BootstrapDialog.confirm('Are you sure you want to do this?', function(result){ 
    // If result is true, then the user confirmed the message 
    if(result) { 
     // Do work here 
     $('input[type=text]').each(function(index, value) { 
      total += parseInt($(value).val() || 0); 
     }); 
     $("#chkTotal").html(total); 
    } 
}); 
+0

謝謝!那完美的作品 – MikeMcClatchie