2014-02-15 11 views
0

내가하려는 것은 각 선택 상자에서 선택한 옵션을 잡고 '제출'을 클릭하여 '저장된'단락에 저장하는 것입니다.선택한 텍스트를 가져와 표시하는 방법은 무엇입니까?

<body> 

<div id="container"> 
<button id="button" onclick="rolldices()">Roll dices</button> 

<span id="dice1">0</span> 
<span id="dice2">0</span> 
<span id="dice3">0</span> 
<span id="dice4">0</span> 
<span id="dice5">0</span> 
<span id="dice6">0</span> 

<br><br><br><br> 

<select id="select1"> 
<option>1 
<option>2 
<option>3 
<option>4 
<option>5 
<option>6 
</select> 

<select id="select2"> 
<option>1 
<option>2 
<option>3 
<option>4 
<option>5 
<option>6 
</select> 

<select id="select3"> 
<option>1 
<option>2 
<option>3 
<option>4 
<option>5 
<option>6 
</select> 

<select id="select4"> 
<option>1 
<option>2 
<option>3 
<option>4 
<option>5 
<option>6 
</select> 

<select id="select5"> 
<option>1 
<option>2 
<option>3 
<option>4 
<option>5 
<option>6 
</select> 

<select id="select6"> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
<option>4</option> 
<option>5</option> 
<option>6</option> 
</select> 

<button id="submit" onclick="submit()">Submit your answer</button> 

<br><br> 

<p id="correct">Correct numbers guessed: </p> 
<p id="stored"></p> 
</div> 
</body> 
</html> 

자바 스크립트 :

여기
var numbers = [ '1', '2', '3', '4', '5', '6' ]; 

var dices = [ 'dice1', 'dice2', 'dice3', 'dice4', 'dice5', 'dice6' ]; 

var select = [ 'select1', 'select2', 'select3', 'select4', 'select5', 'select6'] 

function rolldices() { 

for (var diceindex=0; diceindex<dices.length; diceindex++) { 

var dice_value = Math.floor((Math.random()*numbers.length)); 

document.getElementById("dice" + (diceindex + 1)).innerHTML=numbers[dice_value]; 

} 

} // end of rolldices() 

문제 해결에 나의 시도이다 : 이것은 일종의 작동

function submit() { 

for (var selectindex=0; selectindex<select.length; selectindex++) { 

var e = document.getElementById("select" + (selectindex + 1)); 
var storedNumbers = e.options[e.selectedIndex].text; 

document.getElementById("select" + (selectindex + 1)).text; 
document.getElementById("stored").innerHTML=storedNumbers; 
} 





} // end of submit() 

을하지만, 마지막에만 여기에

내 HTML입니다 selectbox의 텍스트가 "stored"단락에 표시되고 있습니다. 무엇이 잘못 되었습니까? 변화를

function submit() { 

for (var i=0; i<select.length; i++) { 

var e = document.getElementById("select" + (i + 1)); 
var storedNumbers = e.options[e.selectedIndex].text; 

document.getElementById("select" + (i + 1)).text; 
document.getElementById("stored").innerHTML=storedNumbers; 
} 
+1

그리고 당신은 즉으로 발생하는 문제 ...? 무슨 일이 일어나고 있지 않아? 어떤 오류가 발생합니까? 콘솔로 디버깅 해 보셨습니까? – j08691

+0

@ j08691 오류는 발생하지 않지만 저장된 숫자는 내 단락에 표시되지 않습니다. 그래서 나는 무엇이 문제인지 모르겠다. .. –

답변

0

에 당신은 모든 선택 값을 저장해야하고 표시해야 -

+0

두 번 이상 제출하면 새 저장 번호가 추가됩니다. –

+0

@ Duplo W, 모양을 업데이트 해주세요. –

+0

이것은 트릭을 고마워했습니다. –

0

하나의 즉각적인 문제는 당신이 배열로와 계산을위한 변수로 선택 사용하는 것입니다. 같은

var res = ""; //declare outside of function for store all value 
function submit() { 
    //getting all select tags. 
    var allSelect = document.getElementsByTagName('select'); 
    for (var select=0; select < allSelect.length; select++) { 
     var e = document.getElementById("select" + (select + 1)); 
     var storedNumbers = e.options[e.selectedIndex].innerHTML; 
     res +=storedNumbers; //storing the selected values 
    } 
    document.getElementById("stored").innerHTML= res; 
    res = ""; 
} 

DEMO

+0

나는 그것을 바꿨다. 그리고 그것은 반 작동한다. 그러나 단지 마지막 선택 상자의 본문 만 보이고있다. 또한 답안의 마지막 줄에 수정 사항을 추가했습니다.이 행은 innerHTML = storedNumbers; –

+0

이 새로운 문제를 해결하기 위해 내가 무엇을 제안하겠습니까? –

+0

이것은 루프가 진행됨에 따라 storedNumbers가 변경 될 수 있기 때문에 현재 값이 항상 이전 값을 덮어 씁니다. 따라서 마지막 값이 남습니다. – jing3142

0

는 첫째, 나는 HTML 속성으로 핸들러를 부착하지 않는 것이 좋습니다. 논리와 표현을 분리하여 보관해야합니다. 또한 각 필드 (비효율적)에 대해 getElementById을 호출하는 대신 선택 필드를 잡고 필요한 필드를 기준으로 필터링합니다. 방법은 다음과 같습니다.

var selectIds = ['select1', 'select2', 'select3', 'select4', 'select5', 'select6']; 
var selectFields = document.getElementsByTagName('select'); 
var stored = document.getElementById("stored"); 
var submitButton = document.getElementById("submit"); 

submitButton.addEventListener("click", function() { 
    var values = ""; 
    for (var i = 0; i < selectFields.length; i++) { 
     var select = selectFields[i]; 
     // One of our target fields 
     if (selectIds.indexOf(select.getAttribute("id")) >= 0) { 
      values += select.value; 
     } 
    } 

    stored.innerHTML = values; 
}); 

fiddle을 참조하십시오.

업데이트 :

당신이에 대한 참조를 가져하기 전에 요소가 존재해야

. 이를 수행하는 한 가지 방법은 스크립트를 body 태그 맨 아래에 붙이는 것입니다. 예를 들어

:

<html> 
    <body> 
    ... 
    ... 
    ... 
    <script type="text/javascript"> 
     // js here 
    </script> 
    </body> 
</html> 
+0

다음과 같은 오류가 발생합니다. Uncaught TypeError : null의 메서드 'addEventListener'를 호출 할 수 없습니다. –

+0

스크립트 태그가 문서 끝에 있습니까? 아니면'onload' 이벤트 이후에 요소를 선택하겠습니까? 두 가지 모두에 대한 대답이 '아니오'라면 그럴 가능성이 있습니다. – linstantnoodles

+0

브라우저에서는 작동하지 않지만 바이올린에서는 작동합니다. 여기에 누락 된 느낌이 있습니다. submitButton.addEventListener ("click", function() {? –

관련 문제