2014-12-12 2 views
0

동적 양식을 작성합니다. 아이디어는 버튼을 눌러 새 입력 필드를 추가하고 문자열 데이터로 채우고 제출을 클릭하면이 데이터로 올바른 형식으로 div를 생성한다는 것입니다.JS : 새로 생성 된 HTML 요소에 ID를 할당하는 방법

문제가 있지만 첫 번째 입력 필드 만 인식되고 JS가 만든 새 텍스트 필드는 없습니다.

문제는 내가 입력 한 값을 ID로 찾고 있지만 새로 만든 입력의 ID가 무엇인지 모르므로 가져올 수 없습니다.

I've setup a JSFiddle with my prototype하지만 파일을 저장하고 브라우저에서 열면 올바르게 작동하지만 작동하지 않습니다.

<!DOCTYPE html> 
<html> 
<head> 
<title>Test</title> 

<style> 
.HiddenDiv{ 
color: red; 
} 
</style> 

<script> 
//-----CREATES NEW INPUT LINE----- 
var counter1 = 1; 
var limit1 = 5; 

function addInput(divName){ 
    if (counter1 == limit1) { 
      alert("You have reached the limit of adding " + counter1 + " inputs"); 
    } 
    else { 
      var newdiv = document.createElement('div'); 
      newdiv.innerHTML = "<input type='text' name='myInputs[]'>"; 
      document.getElementById(divName).appendChild(newdiv); 
      counter1++; 
    } 
} 
//-----TAKES VALUE AND PRINTS IT ON DIV----- 
var counter2 = 0; //Prevents user from creating multiple nodes on submit 
var limit2 = 1; //Amount of nodes that can be created per input field 

function createNode(){ 
if (counter2 == limit2) { 
//Do nothing 
} 
else { 
var input = document.getElementById('textInput1').value; //Retrieves input 
var newText = document.createElement("li"); //Creates the HTML node 
newText.innerHTML = input; //Sets the node's value to whatever is in the input 

document.getElementById("Form").appendChild(newText); //Adds the node to the div 

counter2++; 
} 
} 
</script> 
</head> 

<body> 
<div id="dynamicInput"> 
Job Requirements<br> 
<input type="text" name="myInputs[]" id="textInput1"> 
</div> 
<form method="POST"> 
<input type="button" value="+" onClick="addInput('dynamicInput');"> 
<input type="button" value="Submit" onClick="return createNode()"> 
</form> 

<div id="Form" class="HiddenDiv"> 
</div> 
</body> 
</html> 
+0

node.setAttribute ('id', 'your id')'를 사용하여 노드 ID를 설정할 수 있습니다. – Ginden

답변

0

가 나는 document.querySelectorAll를 사용하는 것이 더 쉬울 것이라고 생각 :

var inputs = document.querySelectorAll('input[name="myInputs[]"'); 

을 다음 루프에서 입력의 내용을 얻을 수 있습니다 여기에

그리고

는 경우에 코드입니다.

관련 문제