2017-04-09 156 views
0

我不知道如何從輸入框中獲取價值。現在,當我點擊下注按鈕時,它只減去100,我希望在文本框中輸入數值並點擊下注時,它會減去我從餘額中輸入的值。這裏是我的代碼:從js輸入框中獲取價值

HTML:

<div> 
    <input type="text" value=0 name="betAmount"> 
    <button class="betBTN">BET</button> 
</div> 

JS:

document.addEventListener('DOMContentLoaded',function() { 
document.querySelector('.betBTN').addEventListener('click', function() { 
     var toAdd = document.querySelector('div').textContent - 100; 
     document.querySelector('div').innerHTML = ""; 
     document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd); 
    }); 
}); 

有什麼建議?

+0

你有什麼嘗試?這應該是一個快速的Google查詢。 https://www.google.com/?q=Get+value+from+input+box+with+js – Sid

回答

2

替換您100

document.querySelector("input").value; 

這條線將得到input元素

document.addEventListener('DOMContentLoaded',function() { 
 
document.querySelector('.betBTN').addEventListener('click', function() { 
 
     var toAdd = document.querySelector('div').textContent - document.querySelector("input").value; 
 
     document.querySelector('div').innerHTML = ""; 
 
     document.querySelector('div').insertAdjacentHTML('afterbegin', toAdd); 
 
    }); 
 
});
Balance: <div>1000</div> 
 
    <input type="text" value=0 name="betAmount"> 
 
    <button class="betBTN">BET</button>

0

的價值。如果你談論的是輸入的數值,那麼下面的會做這份工作:

document.querySelector('input[name="betAmount"]').value; 

所有輸入元件,無論它們是HTML inputtextareaselect等具有value屬性是所述用戶數據的實際值。