2012-12-18 8 views
0

ID가 to 인 선택 필드가있는 양식이 있습니다. 나는 자바 스크립트 함수 안에서 선택된 값을 얻고 싶다. 처음으로이 함수를 실행하면 선택한 값을 가져 오지 않지만 함수를 두 번째로 실행하면 함수를 가져옵니다. 나는 .text를 시도했다, 이것은 작동하지 않았다. 당신의 도움을 주셔서 대단히 감사합니다..options [e.selectedIndex] .innerHTML 값을 가져 오지 못함

var e = document.getElementById("to"); 
var str = e.options[e.selectedIndex].innerHTML; 
+1

.text가 작동해야하므로 더 많은 코드를 표시하십시오. – epascarello

+0

'

답변

1

처음 실행하면 요소가 렌더링되기 전에 실행하고 있습니까? 그렇다면 document.ready 또는 page load 이벤트를 기다려야합니다.

자바 스크립트

function getText() { 
    var sel = document.getElementById("foo");   
    var option = sel.options[sel.selectedIndex]; 
    //assuming that there is always a selection 
    var text = option.text; 
    var value = option.value; 
    console.log(text, value); 
} 

document.getElementById("bar").onclick = getText; 

getText(); 

select 요소

HTML

<select id="foo"> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
    <option value="3">Three</option> 
</select> 
<button id="bar">Console it</button> 

의 텍스트 및 값을 받고 예를 들어 작업

바이올린에서는 값을 읽을 때로드가 실행 중임을 알 수 있습니다.

1

onReady 함수에 넣으십시오. 아마 페이지가 완전히로드되기 전에 JS가 실행 중입니까? jQuery를 사용하는 경우 :

$(document).ready(function(){ 
    alert($("#to option:selected").text()); 
)}; 
관련 문제