2016-06-22 5 views
1

javascriptスクリプトで宣言された変数をオプションブロックに表示する必要があります。このブロックで選択されたオプションに依存する1〜2つの選択ブロックがあります。オプションタグにjavascript変数を表示する方法

<select name="expiration_year" id="expiration_year" onchange="populate(this.id,'expiration_month','expiration_day')"> 

    <script> 
    //variable declaration in JavaScript 
    var year = new Date().getFullYear(); 
    </script> 

    //I want to display the variable stored in "year" where it is marked in the 
    //following code 
    //this <option value=year> is using the variable correctly, the second 
    //half of the line isnt using the variable (which should have a value 
    //equaling the current year) 
    //instead it simply says year 
    <select> 
    <option value=year>year</option> 
    <option value=year+1>year+1</option> 

    </select>   

Image of what current code produces when run

すべての任意の助けをいただければ幸いです、私は、Webページをコーディングし、Javaスクリプトを使用する新しい極めてです。この質問が既に尋ねられ答えられていれば、申し訳ありません。

答えて

0

オプションを動的に追加するだけでよいでしょう。

// This assumes that this is the only select element on the page. 
// Also, this would have to run in a script block 
// after the select element is added to the page. 
var select = document.querySelector('select'); 
select.options.add(new Option(year)); 
select.options.add(new Option(year + 1)); 

// etc. 
+0

お返事ありがとうございます!私の究極の目標は、ページ上に合計3つの選択肢があることです。依存の順序は年==>月==>日である。年月日は選択の名前です。複数の選択肢があることを反映するために質問を更新しました。再度、感謝します! – brandontod97

関連する問題