2012-04-29 5 views
1

選択リストで作成した属性にアクセスしようとしています。selectリストにjavascriptで作成した属性を使用する

<script language="JavaScript"> 
function updateUrl() 
    { 
     var newUrl=document.getElementById('test').car; 
     alert(newUrl); 
    } 
</script> 

<input type="text" id="test" car="red" value="create Attribute test" size="40"/> 
<input type="button" value="submit" onclick="updateUrl();"> 

それは私に未定義を与え続けます。私はどのように属性の車から文字列赤を取得するのですか?

編集。私は、選択リストでそれを試してみました、それはこの試しください

<select name= "test" id= "test" onChange= "updateUrl()"> 
    <option value="1" selected="selected" car="red">1</option> 
    <option value="2" car="blue" >2</option> 
    <option value="3" car="white" >3</option> 
    <option value="4" car="black" >4</option>  
</select> 
+0

同じ質問を2回転記しないでください。 –

答えて

8

をヌル警告:<select>について

var newUrl = document.getElementById('test').getAttribute('car'); 

EDIT

を、あなたが選択した<option>要素を検討する必要がなく、 <select>自体:

var select = document.getElementById('test'); 
select.options[select.selectedIndex].getAttribute('car'); 
+0

いいえ、試してみてください。http://stackoverflow.com/a/10369746/908879 – ajax333221

+0

@ ajax333221リンク先の質問は終了する必要があります。 – bfavaretto

関連する問題