2017-07-26 69 views
0

我有一個遊戲,你可以在每次回合中輸入你的分數到輸入框中。我寫了一個for循環來添加每個回合的總數,並將它顯示在「Total Score」框中。然而,在本場比賽中,如果在所有回合結束時你的「總得分」大於或等於50,你會得到10分的獎勵。我需要幫助編寫這個IF語句在JS

所以我創建了另一個名爲「Total」的輸入框。我想創建一個IF語句,以便如果「總分」輸入框中的數字大於或等於50,則您的分數加上10分獎金將顯示在其下方的「總計」框中。我怎樣才能做到這一點?

這裏是我的代碼:

//input form 

Turn 1: <input onblur="findTotal()" type="text" name="qty"> 
<br> 
Turn 2: <input onblur="findTotal()" type="text" name="qty"> 
<br> 
Trun 3: <input onblur="findTotal()" type="text" name="qty"> 
<br> 
<b>Total Score:</b> <input type="text" name="TotalScore" id="TotalScore"> 
<br> 
Bonus (+10): <input type="text" name="bonus"> 
<br> 
<b>Total:</b> <input type="text" name="Total"> 

//for loop 

function findTotal() { 
    var arr = document.getElementsByName('qty'); 
    var tot = 0; 
    for (var i = 0; i < arr.length; i++) { 
     if (parseInt(arr[i].value)) 
      tot += parseInt(arr[i].value); 
    } 
    document.getElementById('Total').value = tot; 
} 
onblur = "findTotal()" 

//my attempt at the IF statement ("alert hello" is just a place holder) 

var tots = document.getElementById('TotalScore'); 

if (tots.value >= 50) { 
    alert("hello"); 
} 
+2

您的findTotal函數將運行一次外部的代碼,當頁面加載 - 也許你要移動的功能,裏面的代碼? –

回答

0

提供文本框的id,

<b>Total:</b> <input type="text" id="tots" name="Total"> 

和使用,如果是,

if($('#tots').value>=50){} 
+0

我認爲問題代碼中沒有jQuery,它也不包含jQuery標籤。 – Colin

+0

他已經讀取沒有jQuery的值 – lumio

+0

我需要幫助編寫這個IF語句在JS中,問題的標題,所以我在JavaScript中做了。謝謝你的問候。 – Rox

1

你可以嘗試檢查,看看用戶在findTotal函數結束時獲得了獎金(無論如何您剛剛完成計算total score):

function findTotal() { 
 
    var arr = document.getElementsByName('qty'); 
 
    var tot = 0; 
 
    for (var i = 0; i < arr.length; i++) { 
 
    if (parseInt(arr[i].value)) 
 
     tot += parseInt(arr[i].value); 
 
    } 
 

 
    document.getElementById('TotalScore').value = tot; 
 

 
    var bonus = tot >= 50 ? 10 : ''; 
 
    document.getElementById('bonus').value = bonus; 
 
    document.getElementById('Total').value = tot + bonus; 
 
}
Turn 1: <input onblur="findTotal()" type="text" name="qty"> 
 
<br> Turn 2: <input onblur="findTotal()" type="text" name="qty"> 
 
<br> Turn 3: <input onblur="findTotal()" type="text" name="qty"> 
 
<br> 
 
<b>Total Score: </b> <input disabled="true" type="text" name="TotalScore" id="TotalScore"> 
 
<br> Bonus: <input disabled="true" type="text" id="bonus"> 
 
<br> 
 
<b>Total:</b> <input disabled="true" type="text" id="Total">