2017-04-16 5 views
0

javascript関数でフォーム要素の入力値を使用します。しかし、変数を宣言すると、フォームから入力値が引き出されません。代わりに、デバッガはちょうど言っている。 ""フォーム番号入力が変数としてjavascriptに転送されない

マイコードは次のとおりです。

HTML:

<input type="number" name="stack" id="stack" min="1" max="600" placeholder="Big Blinds" required> 

Javascriptを:

var stack = document.getElementById("stack").value; 

何かアドバイスは素晴らしいことです。ありがとう。

答えて

0

input要素がまだ空のときに値を取得しているようです。変数を設定するコードは、入力要素にデータが入力された後に実行される関数の内部にカプセル化されていないように見えるので、コードはすぐに実行されます。

の値が入力された後に値が得られていることを確認する必要があります。

これは、特定のタイミングで発生するイベント処理関数を追加することによって実行されます。 (keyup、​​、input、フォームのsubmit、ボタンclickなど)のさまざまなイベントがあります。次に、ボタンをクリックしたときの値の取得例を示します。

// Get a reference to the button that will trigger the event function 
 
var btn = document.getElementById("btn"); 
 

 
// Get a reference to the input element (do this outside of the function that 
 
// will need it so you don't wind up scanning the document for it over and over). 
 
// Also, set the variable to the element itself, not a property of the element so 
 
// that if you ever need a different property, you don't have to scan the document 
 
// for the element again: 
 
var input = document.getElementById("stack"); 
 

 
// If you intend to use the value of the element across several functions, declare a 
 
// variable that will hold the value outside of all of them. 
 
var stack = null; 
 

 
// Set the button up to call a function when it gets clicked. 
 
btn.addEventListener("click", function(){ 
 
    // When clicked, get the value 
 
    stack = input.value; 
 

 
    // Do whatever you want with the stored value. 
 
    console.log(stack); 
 
});
<input type="number" name="stack" id="stack" min="1" max="600" placeholder="Big Blinds" required> 
 
<button id="btn">Get Value</button>

+0

おかげでチームメイト - たくさん助け。 –

関連する問題