2011-01-26 2 views
1

아래 html이 있다고 가정합니다. 가장 효율적인 방법은 무엇입니까?jQuery를 사용하여 스팬에 체크 된 값의 값으로 채우기

<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a"> 
    <input type="checkbox" value="b"> 
    <input type="checkbox" value="c"> 
    <input type="checkbox" value="d"> 
</div> 

// on click of a checkbox, span should be populated by the checked boxes 
// <span class="text">a b d</span> 

답변

2
<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a"> 
    <input type="checkbox" value="b"> 
    <input type="checkbox" value="c"> 
    <input type="checkbox" value="d"> 
</div> 

JQuery와 부분

var n = jQuery("div.allboxes :checkbox").map(function(){ 
     return jQuery(this).val();}).get().join(" "); 
alert(n); 

작업 예제 here

1
jQuery('input:checked') 

작은을 유지하고 HTML을 수정하는 것이 중요하다, 그래서 체크 박스의 목록이 수백로 성장할 수 있습니다. 속성 값 사이에는 쉼표를 사용할 수 없습니다.

1

정리 html로 :

<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a"> 
    <input type="checkbox" value="b"> 
    <input type="checkbox" value="c"> 
    <input type="checkbox" value="d"> 
</div> 

그리고 당신은 다음과 같이 수행 할 수 있습니다

$('.allboxes input').change(function() { 
    var whichSelected = []; 
    $.each($('.allboxes input:checked'), function(a,b) { 
     whichSelected.push($(b).val()); 
    }); 
    $('.text').text(whichSelected.join(' ')); 
}); 

바이올린의 : http://jsfiddle.net/amirshim/sDDps/3/

1

나는 모든 체크 상자를 분석하지 않는 것이 좋습니다. 전역 배열을 사용하여 span에 채울 값을 저장하십시오.

var globalvar = new Array(); 
function populate(obj){ 
globalvar .push(obj.value)); 
$('.text').text(globalvar.join(' ')); 
} 

다음과 같이 html을 만드십시오. 또는 일부 기능을 실행하여 해당 기능을 한 번만 삽입하십시오.

<span class="text"></span> 
<div class="allboxes"> 
    <input type="checkbox" value="a" onclick="populate(this)"> 
    <input type="checkbox" value="b" onclick="populate(this)"> 
    <input type="checkbox" value="c" onclick="populate(this)"> 
    <input type="checkbox" value="d" onclick="populate(this)"> 
</div> 
관련 문제