HTML에서 "모두 선택"확인란을 구현하는 방법은 무엇입니까?
확인란이 여러 개인 HTML 페이지가 있습니다.
"모두 선택"이라는 이름의 확인란이 하나 더 필요합니다. 이 확인란을 선택하면 HTML 페이지의 모든 확인란이 선택되어 있어야합니다. 어떻게해야합니까?
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var checkbox in checkboxes)
checkbox.checked = source.checked;
}
</script>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
최신 정보:
for each...in
구조는이 경우 적어도, 사파리 5, 크롬 5에이 코드는 모든 브라우저에서 작동합니다, 작동하지 않는 것 :
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
jQuery 사용 :
// Listen for click on toggle checkbox
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
HTML :
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />
<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />
아무도 jQuery를 사용하여 이런 식으로 대답하지 않았는지 확실하지 않습니다 .
$( '#container .toggle-button' ).click( function () {
$( '#container input[type="checkbox"]' ).prop('checked', this.checked)
})
깨끗하고 루프 또는 if / else 절이 없으며 매력으로 작동합니다.
선택을 해제하려면 :
$('#select_all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
}
else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
아무도 언급하지 않은 것에 놀랐습니다 document.querySelectorAll()
. 순수 JavaScript 솔루션은 IE9 +에서 작동합니다.
function toggle(source) {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i] != source)
checkboxes[i].checked = source.checked;
}
}
<input type="checkbox" onclick="toggle(this);" />Check all?<br />
<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});
});
</script>
<div id="wrapper">
<li style="margin-top: 20px">
<input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
<ul>
<li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
<li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
<li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
<li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
</ul>
</li>
</ul>
<ul>
<li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
<ul>
<li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
<li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
<li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
</ul>
</li>
</ul>
</li>
</div>
정중하게 확인 및 확인을 취소하는 약간 변경된 버전
$('#select-all').click(function(event) {
var $that = $(this);
$(':checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
전화 document.getElementsByName("name")
하면을 (를)받습니다 Object
. 의 .item(index)
모든 항목을 통과하는 데 사용Object
HTML :
<input type="checkbox" onclick="for(c in document.getElementsByName('rfile')) document.getElementsByName('rfile').item(c).checked = this.checked">
<input type="checkbox" name="rfile" value="/cgi-bin/">
<input type="checkbox" name="rfile" value="/includes/">
<input type="checkbox" name="rfile" value="/misc/">
<input type="checkbox" name="rfile" value="/modules/">
<input type="checkbox" name="rfile" value="/profiles/">
<input type="checkbox" name="rfile" value="/scripts/">
<input type="checkbox" name="rfile" value="/sites/">
<input type="checkbox" name="rfile" value="/stats/">
<input type="checkbox" name="rfile" value="/themes/">
<html>
<head>
<script type="text/javascript">
function do_this(){
var checkboxes = document.getElementsByName('approve[]');
var button = document.getElementById('toggle');
if(button.value == 'select'){
for (var i in checkboxes){
checkboxes[i].checked = 'FALSE';
}
button.value = 'deselect'
}else{
for (var i in checkboxes){
checkboxes[i].checked = '';
}
button.value = 'select';
}
}
</script>
</head>
<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />
<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>
</html>
간단한 솔루션을 사용 하면 양식의 지정된 부분에있는 모든 확인란을 선택적으로 선택 / 선택 취소 할 수 있으며 각 확인란마다 다른 이름 을 사용 하여 양식을 게시 한 후 쉽게 확인할 수 있습니다.
자바 스크립트 :
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++) {
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
HTML 예 :
<p><input onClick="setAllCheckboxes('actors', this);" type="checkbox" />All of them</p>
<div id="actors">
<p><input type="checkbox" name="kevin" />Spacey, Kevin</p>
<p><input type="checkbox" name="colin" />Firth, Colin</p>
<p><input type="checkbox" name="scarlett" />Johansson, Scarlett</p>
</div>
나는 그것을 좋아하면 좋겠!
이 간단한 JQuery를 사용해보십시오.
$('#select-all').click(function(event) {
if (this.checked) {
$(':checkbox').prop('checked', true);
} else {
$(':checkbox').prop('checked', false);
}
});
JavaScript는 최선의 방법입니다. 아래 링크는 버튼을 사용하여 모두를 선택 취소 / 선택하는 예입니다. 확인란을 사용하도록 적용하려고 시도 할 수 있습니다. onClick 속성에서 '모두 선택'확인란을 사용하십시오.
모든 확인란을 선택 또는 선택 해제하는 Javascript 기능
이 페이지는 더 간단한 예입니다
http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html
이 샘플은 확인란 변수 이름이 다른 기본 JavaScript와 함께 작동합니다 (예 : "foo"가 아님).
<!DOCTYPE html>
<html>
<body>
<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
var node_list = document.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i < node_list.length; i++)
{
var node = node_list[i];
if (node.getAttribute('type') == 'checkbox')
{
checkboxes.push(node);
}
}
return checkboxes;
}
function toggle(source) {
checkboxes = getcheckboxes();
for(var i=0, n=checkboxes.length;i<n;i++)
{
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>
<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>
</body>
</html>
jquery에 대한 최상위 답변을 채택하는 경우 click 함수에 전달 된 객체는 원래 확인란 객체가 아니라 EventHandler라는 것을 기억하십시오. 따라서 코드 shoudl은 다음과 같이 수정됩니다.
HTML
<input type="selectThemAll" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
자바 스크립트
jQuery("[name=selectThemAll]").click(function(source) {
checkboxes = jQuery("[name=foo]");
for(var i in checkboxes){
checkboxes[i].checked = source.target.checked;
}
});
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="Item 1">Item 1</asp:ListItem>
<asp:ListItem Value="Item 2">Item 2</asp:ListItem>
<asp:ListItem Value="Item 3">Item 3</asp:ListItem>
<asp:ListItem Value="Item 4">Item 4</asp:ListItem>
<asp:ListItem Value="Item 5">Item 5</asp:ListItem>
<asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>
<script type="text/javascript">
function checkAll(obj1) {
var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');
for (var i = 0; i < checkboxCollection.length; i++) {
if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
checkboxCollection[i].checked = obj1.checked;
}
}
}
</script>
작업이 완료되어야합니다.
$(':checkbox').each(function() {
this.checked = true;
});
$(document).ready(function() {
$(document).on(' change', 'input[name="check_all"]', function() {
$('.cb').prop("checked", this.checked);
});
});
jQuery와 녹아웃 사용하기 :
이 바인딩 기본 확인란은 기본 확인란과 동기화 상태를 유지하므로 모든 확인란을 선택하지 않으면 확인란이 선택 해제됩니다.
ko.bindingHandlers.allChecked = {
init: function (element, valueAccessor) {
var selector = valueAccessor();
function getChecked () {
element.checked = $(selector).toArray().every(function (checkbox) {
return checkbox.checked;
});
}
function setChecked (value) {
$(selector).toArray().forEach(function (checkbox) {
if (checkbox.checked !== value) {
checkbox.click();
}
});
}
ko.utils.registerEventHandler(element, 'click', function (event) {
setChecked(event.target.checked);
});
$(window.document).on('change', selector, getChecked);
ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
$(window.document).off('change', selector, getChecked);
});
getChecked();
}
};
html로 :
<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>
여기 양식이 있습니다.
<form action="#">
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
<fieldset>
<legend>Loads of checkboxes</legend>
<p><label><input type="checkbox" /> Option 1</label></p>
<p><label><input type="checkbox" /> Option 2</label></p>
<p><label><input type="checkbox" /> Option 3</label></p>
<p><label><input type="checkbox" /> Option 4</label></p>
</fieldset>
</form>
그리고 여기 jquery :
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
예를 들어 5 개의 확인란이 있고 모두 확인을 클릭하고 모두 확인을 클릭 한 경우, 이제 각 5 개의 확인란을 클릭하여 모든 확인란을 선택 취소하면 마지막 확인란을 선택 취소 할 때까지 모든 확인란도 선택 해제되어 있습니다
$("#select-all").change(function(){
$(".allcheckbox").prop("checked", $(this).prop("checked"))
})
$(".allcheckbox").change(function(){
if($(this).prop("checked") == false){
$("#select-all").prop("checked", false)
}
if($(".allcheckbox:checked").length == $(".allcheckbox").length){
$("#select-all").prop("checked", true)
}
})
내가 말할 수없는 답변으로 여기 : Can Berk Güder의 솔루션을보다 일반적인 방식으로 작성하므로 다른 확인란의 기능을 재사용 할 수 있습니다
<script language="JavaScript">
function toggleCheckboxes(source, cbName) {
checkboxes = document.getElementsByName(cbName);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>
<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>
다음은 backbone.js 구현입니다.
events: {
"click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {
var checkboxes = document.getElementsByName('options');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = event.currentTarget.checked;
}
},
html
<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3
자바 스크립트
$(':checkbox.all').change(function(){
$(':checkbox.item').prop('checked', this.checked);
});
1 : onchange 이벤트 핸들러 추가
<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>
2 : 확인 / 확인되지 않은 코드를 처리하도록 코드 수정
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
동일한 양식에 다른 확인란 세트 가있을 수 있습니다 . 다음은 바닐라 자바 스크립트 함수 document.getElementsByClassName을 사용하여 클래스 이름별로 확인란을 선택 / 선택 취소하는 솔루션입니다.
모두 선택 버튼
<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All
선택할 확인란 중 일부
<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />
자바 스크립트
function selectAll() {
var blnChecked = document.getElementById("select_all_invoices").checked;
var check_invoices = document.getElementsByClassName("check_invoice");
var intLength = check_invoices.length;
for(var i = 0; i < intLength; i++) {
var check_invoice = check_invoices[i];
check_invoice.checked = blnChecked;
}
}
이 간단한 코드를 사용할 수 있습니다
$('.checkall').click(function(){
var checked = $(this).prop('checked');
$('.checkme').prop('checked', checked);
});
jQuery를 사용하여 단축 버전으로 작성
모두 선택 체크 박스
<input type="checkbox" id="chkSelectAll">
어린이 확인란
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
jQuery
$("#chkSelectAll").on('click', function(){
this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);
})
어쩌면 조금 늦었지만 모두 확인란을 선택할 때 모든 확인란을 선택한 다음 아래 확인란 중 하나를 선택 취소하는 시나리오를 처리해야한다고 생각합니다.
이 경우 모두 확인 확인란을 자동으로 선택 취소해야합니다.
또한 모든 확인란을 수동으로 확인할 때 모든 확인란을 자동으로 선택해야합니다.
두 개의 이벤트 핸들러가 필요합니다. 하나는 모두 선택 상자와 아래의 단일 상자를 클릭 할 때 사용합니다.
// HANDLES THE INDIVIDUAL CHECKBOX CLICKS
function client_onclick() {
var selectAllChecked = $("#chk-clients-all").prop("checked");
// IF CHECK ALL IS CHECKED, AND YOU'RE UNCHECKING AN INDIVIDUAL BOX, JUST UNCHECK THE CHECK ALL CHECKBOX.
if (selectAllChecked && $(this).prop("checked") == false) {
$("#chk-clients-all").prop("checked", false);
} else { // OTHERWISE WE NEED TO LOOP THROUGH INDIVIDUAL CHECKBOXES AND SEE IF THEY ARE ALL CHECKED, THEN CHECK THE SELECT ALL CHECKBOX ACCORDINGLY.
var allChecked = true;
$(".client").each(function () {
allChecked = $(this).prop("checked");
if (!allChecked) {
return false;
}
});
$("#chk-clients-all").prop("checked", allChecked);
}
}
// HANDLES THE TOP CHECK ALL CHECKBOX
function client_all_onclick() {
$(".client").prop("checked", $(this).prop("checked"));
}
간단하고 요점 :
jQuery-버튼이나 div 또는 레이블 요소를 클릭하면. 페이지에서 모든 확인란을 선택 해제하십시오. 좀 더 구체적으로 만들려면 : checkbox를 조정해야합니다.
jQuery("#My-Button").click(function() {
jQuery(':checkbox').each(function() {
if(this.checked == true) {
this.checked = false;
} else {
this.checked = true;
}
});
});
참고 URL : https://stackoverflow.com/questions/386281/how-to-implement-select-all-check-box-in-html
'Programming' 카테고리의 다른 글
Eclipse 오류 : 'Java Virtual Machine을 작성하지 못했습니다' (0) | 2020.05.06 |
---|---|
폴더의 파일 이름을 순차 번호로 바꾸기 (0) | 2020.05.06 |
Rails에서 현재 경로를 어떻게 알 수 있습니까? (0) | 2020.05.06 |
선택한 UITableView 셀을 선택 취소하는 방법은 무엇입니까? (0) | 2020.05.06 |
random.choice의 가중치 버전 (0) | 2020.05.06 |