2013-07-25 3 views
0

나는 등록 양식을 작성하려고합니다. 이 등록 양식은 "주소 1"이라는 텍스트 상자로 구성되며 그 근처에 "주소 추가"버튼이 있습니다. 단추의 기능 - 더 많은 주소에 대한 텍스트 상자를 추가합니다. 이전 주소 상자 근처의 단추가 "제거"로 변경되어 주소 상자와 단추가 제거됩니다. 문제는 다음과 같습니다. 텍스트 상자를 순서대로 설정해야합니다 - 1,2,3, ... - 이름과 ID를 변경해야합니다. 예를 들어 - 주소 상자 번호 4 (name, id = "address4")를 제거하면 다음 텍스트 상자의 이름과 ID가 모두 1 씩 감소합니다. for 루프에서이 작업을 시도합니다. 설명하기가 어렵 기 때문에 코드를 제공합니다. 귀하의 대시 보드에서 'document.getElementById ("address"+ n) "라고 쓰십시오. 도트 ID 나 이름 또는 값 뒤에 쓸 수있는 목록에 표시되지 않은 것을 볼 수 있습니다. 나는이 점에 변수가 있기 때문에 그것이 내가 생각하는 문제 다. 이제 코드는 다음과 같습니다.이름 및 ID 변경

<html> 
<head> 
    <title>Untitled Page</title> 
    <script type="text/javascript"> 
     var n1 = 1; //counting the buttons and divs. doesn't decrease. 
        //In another words - it counts the number of calls to Add() 
     var n3 = 1; //counting the address text fields. 
        //It being reduced and increased so that it will represent the exact number of text fields 
     function Add() { 
      n1++; 
      n3++; 
       s1 = "<div id='div" + n1 + "'>"; 
       s1 += "Address <input type='text' name='address" + n3 + "' id='address" + n3 + "' />"; 
       s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add();' /><br />"; 
       s1 += "</div>"; 
       var n2 = n1 - 1; 
       document.getElementById('div' + n2).insertAdjacentHTML('afterEnd', s1); 
       document.getElementById('add' + n2).onclick = function() { Remove(n2, (n3-1)); }; 
       document.getElementById('add' + n2).value = 'Remove'; 
     } 
     function Remove(nn1, nn2) { //nn1 - div number to remove. nn2 - the address field number in this div 
      var parent = document.getElementById('barcode'); 
      var child = document.getElementById('div' + nn1); 
      parent.removeChild(child); 
      for (nn2 += 1; nn2 <= n3; nn2++) { 
       var n2 = nn2 - 1; //nn2 - current address text field. n2 - the new number for the address field 
       document.getElementById('address' + nn2).setAttribute('name', 'address' + n2); 
       document.getElementById('address' + nn2).setAttribute('id', 'address' + n2); 
       document.getElementById('address' + n2).setAttribute('value', 'address' + n2); 
       // try: document.getElementById('address' + nn2).name='address'+n2. doesn't work (for me) 
      } 
      n3--; 
     } 
     var check = false; 
    </script> 
</head> 
<body> 
    <form name='barcode' id='barcode' action="" > 
     <div id='div1'> 
     Address <input type='text' name='address1' id='address1' /> 
     <input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br /> 
     </div></form> 
</body> 
</html> 

죄송합니다.이 코드에는 주소 입력란에 연결된 내용 만 표시되어 있으며 의견을 추가했습니다. 대단히 감사합니다!

편집 : 이미이 문제를 해결하기 위해이 코드의 버그가 표시되지 않는 것을 잊었습니다. 코드를 변경하기 전에 모든 div, 텍스트 필드 및 버튼 추가/제거를 명령하여 모든 기존 항목이 항상 순서대로 번호가 매겨집니다 (1, 2, 3, ...). 2 번 추가 단추를 클릭 한 다음 첫 번째 주소 필드를 제거한 다음 추가 단추를 다시 클릭하면 다음 코드의 문제를 볼 수 있습니다.

<html> 
<head> 
    <script type="text/javascript"> 
     var n1 = 1; 
     function Add() { 
       n1++; 
       s1 = "<div id='div" + n1 + "'>"; 
       s1 += "Address <input type='text' name='address" + n1 + "' id='address" + n1 + "' />"; 
       s1 += "<input type='button' name='add" + n1 + "' id='add" + n1 + "' value='Add Branch' onclick='Add()' /><br />"; 
       s1 += "</div>"; 
       var n2 = n1 - 1; 
       document.getElementById('div' + (n2)).insertAdjacentHTML('afterEnd', s1); 
       document.getElementById('add' + (n2)).onclick = function() { Remove(n2); }; 
       document.getElementById('add' + (n2)).value = 'Remove'; 
     } 
     function Remove(n) { 
      var parent = document.getElementById('barcode'); 
      var child = document.getElementById('div' + n); 
      parent.removeChild(child); 
      for (n += 1; n <= n1; n++) { 
       var n2 = n1 - 1; 
       document.getElementById('add' + n).onclick = function() { Remove(n2); }; 
       document.getElementById('address' + n).setAttribute('name', 'address' + n2); 
       document.getElementById('add' + n).setAttribute('name', 'add' + n2); 
       document.getElementById('address' + n).setAttribute('id', 'address' + n2); 
       document.getElementById('add' + n).setAttribute('id', 'add' + n2); 
       document.getElementById('div' + n).setAttribute('id','div' + n2); 
      } 
      n1--; 
      document.getElementById('add' + n1).onclick = function() { Add() }; 
     } 
    </script> 
</head> 
<body> 
    <form name='barcode' id='barcode' action="" > 
      <div id='div1'> 
      Address <input type='text' name='address1' id='address1' /> 
      <input type='button' name='add1' id='add1' value='Add Branch' onclick='Add();' /><br /> 
      </div> 
     </form> 
</body> 
</html> 
+0

마지막으로 항상 제거하지 않는 이유는 무엇입니까? –

+0

정확히 이것을 수행하고 싶습니까? 그냥 텍스트 상자를 제거 하시겠습니까? –

+0

이것은 동적입니다. 매번 모든 숫자를 변경할 필요가 없습니다. 새 번호가 "최대"로 고유한지 확인하십시오. – Hogan

답변

2

나는 당신이 주소의 순서를 유지하기 위해 너무 열심히 조금 노력하고 생각하고 나는 그것을 할 수있는 일반적인 이유 (있는 경우, 귀하의 질문에 추가하십시오)이 표시되지 않습니다.

입력과 같이 고유 색인을 추가하면 항상 다른 순서로 정렬됩니다.

여기에 당신이 할 수있는 작업은 다음과 같습니다 기능을 추가하고 당신이 그 요소를 원하는대로 변경을 할 수 있습니다 제거하고 내부에

이벤트 호출을 전달합니다. 예를 들어

당신의 Remove 기능과 같을 것이다 (당신이 Remove(this); 콜 것) :

function Remove(callerButton) { 
    var parent = document.getElementById('barcode'); 

    var child = callerButton.parentNode; 
    // child is the DIV you want to remove 
    parent.removeChild(child); 
    n3--; 
} 

당신은 모든 당신이 지금하고있는 정렬 할 필요가 없습니다 것입니다 이런 식으로. 당신이 남아있는 모든 요소에 액세스 할 수 끝에

:

var addresses = document.getElementById("barcode").getElementsByTagName("input"); 

for(var i = 0; i < addresses.length; i++) { 
    if(addresses[i].type == "text") { 
     // I'm printing them in the console, you can do with it whatever you like 
     // If you want to exclude the one with "Add Branch in front of it you can validate for address+n1 
     console.log("Element.id : " + addresses[i].id + " - Element.value: "+ addresses[i].value); 
    } 
} 

나는 (형태 나머지 필드를 보여주기 위해 제출 버튼을 추가) 이러한 변화와 jsFiddle을 추가했습니다.

문제가 해결되는지 확인하십시오.

+0

예, 작동합니다! 매우 감사합니다.(주소를 설정하여 다른 페이지로 보내고 인쇄하여 프로젝트의 데이터베이스에 삽입해야했습니다.) –