2013-03-20 3 views
0

번호가 매겨진 입력을 이름에 추가하려고합니다 (이미 성공적으로 수행 되었음). 비어 있으면 입력 할 수 없습니다. 이 코드를 사용하면 모든 검색 클래스 입력이 지워집니다. 나는 비어있는 것들만 지우고 싶다. 여기 내 시도입니다 :개별적으로 입력 제거

<script type="text/javascript"> 
// contains the counter for elements added 
window.__buttonClickCounter = 1; 

// Keep reference to container 
var c = document.getElementById('inputs'); 

// Click handler that appends to the contents of the container 
var clickhandler = function() { 
    c.innerHTML = c.innerHTML + "<input class='search' style='margin-bottom:4px;' type='search'   name='word" + window.__buttonClickCounter + "'/>"; 
    window.__buttonClickCounter++; 

    $('#removebtn').click(function() { 
     $('.search').remove(); 
    }); 
} 
</script> 

고마워요!

+0

당신이 jQuery를 사용하고 있습니까? –

+0

removebtn을 클릭하면 입력 내용을 삭제하는 방법을 알 수있는 방법 –

답변

0

당신은 다음과 같이 jQuery를 사용하여 쓸 수 있습니다

$(function(){ 
    var counter = 0; 
    $('#addbtn').click(function(){ 
     $('#inputs').append('<input class="search" style="margin-bottom:4px;" type="search"   name="' + counter++ + '"/>') 
    }); 

    $('#removebtn').click(function(){ 
     $('.search').each(function(){ 
      var $this = $(this); 
      if(!$this.val()){ 
       $this.remove() 
      } 
     });  
    }); 
}) 

데모 : Fiddle 당신은 빈을 따라서 (이 같은 .remove()를 호출만을 제거하기 전에 jQuery 오브젝트에서 비어 있지 않은 사람을 필터링 할 수 있습니다

+0

메가 덕분에 –

0

사람) 다음 .filter() 콜백 true을 반환

$('#removebtn').click(function() { 
    $('.search').filter(function() {return !this.value}).remove(); 
}); 

경우, 항목이 유지됩니다. false을 반환하면 값은 결과 jQuery 객체에서 제거됩니다. 따라서 이것은 모든 .search 개체로 시작하여 !this.valuetrue 인 개체 만 유지합니다. 즉, this.value이 거짓 (예 : 공백) 인 개체를 유지하므로 공백 인 경우에만 .remove()이 호출됩니다.


또는 좀 더 재사용 방법 :

// Reusable jQuery method for filtering out non-empty input values 
// Also filters out items that don't have a `.value` property 
$.fn.filterNonEmpty = function() { 
    return this.filter((function() {return !this.value}); 
}; 

// now use this new jQuery method 
$('#removebtn').click(function() { 
    $('.search').filterNonEmpty().remove(); 
});