배열에서 선택한 모든 확인란 가져오기
다음 체크박스가 있습니다.
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
기타 등등.이들 중 약 6개는 수작업으로 코딩되어 있기 때문에(즉, DB에서 가져오지 않음) 한동안 동일한 상태를 유지할 수 있습니다.
질문입니다. 어떻게 하면 그것들을 모두 배열로 만들 수 있을까요? (javascript로) AJAX를 만들 때 사용할 수 있을까요?$.post
Jquery를 사용하여 요청합니다.
무슨 생각 있어?
편집: 선택한 확인란을 배열에만 추가합니다.
포맷 완료:
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
잘되면 좋겠는데.
순수 JS
jQuery를 사용하지 않으시는 분들을 위해
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
var chk_arr = document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;
for(k=0;k< chklength;k++)
{
chk_arr[k].checked = false;
}
테스트하지 않았지만 작동해야 합니다.
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox[name=type]:checked").each(function() {
selected.push($(this).val());
});
});
</script>
ES6 버전:
const values = Array
.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
function getCheckedValues() {
return Array.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
}
const resultEl = document.getElementById('result');
document.getElementById('showResult').addEventListener('click', () => {
resultEl.innerHTML = getCheckedValues();
});
<input type="checkbox" name="type" value="1" />1
<input type="checkbox" name="type" value="2" />2
<input type="checkbox" name="type" value="3" />3
<input type="checkbox" name="type" value="4" />4
<input type="checkbox" name="type" value="5" />5
<br><br>
<button id="showResult">Show checked values</button>
<br><br>
<div id="result"></div>
임시 변수가 필요 없는 순수 JavaScript:
Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
이렇게 하면 효과가 있습니다.
$('input:checked');
확인할 수 있는 다른 요소가 없는 것 같습니다만, 있다면 좀 더 구체적으로 설명해야 합니다.
$('input:checkbox:checked');
$('input:checkbox').filter(':checked');
MoTools 1.3(작성 시점의 최신):
var array = [];
$$("input[type=checkbox]:checked").each(function(i){
array.push( i.value );
});
바닐라 JS 를 사용하는 경우는, @zahid-ulla 와 같이 루프를 회피할 수 있습니다.
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
ES6의 동일한 코드가 훨씬 더 좋아 보입니다.
var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
document.getElementById('serialized').innerText = JSON.stringify(values);
}
label {
display: block;
}
<label>
<input type="checkbox" name="fruits[]" value="banana">Banana
</label>
<label>
<input type="checkbox" name="fruits[]" value="apple">Apple
</label>
<label>
<input type="checkbox" name="fruits[]" value="peach">Peach
</label>
<label>
<input type="checkbox" name="fruits[]" value="orange">Orange
</label>
<label>
<input type="checkbox" name="fruits[]" value="strawberry">Strawberry
</label>
<button onclick="serialize()">Serialize
</button>
<div id="serialized">
</div>
Javascript에서는 다음과 같습니다(Demo Link).
// get selected checkboxes
function getSelectedChbox(frm) {
var selchbox = [];// array that will store the value of selected checkboxes
// gets all the input tags in frm, and their number
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
return this.value;
}).get();
최신 브라우저에서 vanilla JS를 사용하는 다른 방법(IE 지원 없음, 안타깝게도 쓰기 시 iOS Safari 지원 없음)은 FormData.getAll()을 사용하는 것입니다.
var formdata = new FormData(document.getElementById("myform"));
var allchecked = formdata.getAll("type"); // "type" is the input name in the question
// allchecked is ["1","3","4","5"] -- if indeed all are checked
사용방법:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
체크박스를 켜면 체크박스의 값을 더하고 체크박스를 끄면 값을 뺍니다.
$('#myDiv').change(function() {
var values = 0.00;
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values=values+parseFloat(($(this).val()));
// }
});
console.log( parseFloat(values));
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4.00" />
<input type="checkbox" name="type" value="3.75" />
<input type="checkbox" name="type" value="1.25" />
<input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
입력명별 체크박스 선택
var category_id = [];
$.each($("input[name='yourClass[]']:checked"), function(){
category_id.push($(this).val());
});
Array.from($(".yourclassname:checked"), a => a.value);
Jquery 사용
모든 입력에 클래스만 추가하면 됩니다. 클래스 "소스"를 추가해야 합니다. 물론 변경할 수 있습니다.
<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />
<script type="text/javascript">
$(document).ready(function() {
var selected_value = []; // initialize empty array
$(".source:checked").each(function(){
selected_value.push($(this).val());
});
console.log(selected_value); //Press F12 to see all selected values
});
</script>
function selectedValues(ele){
var arr = [];
for(var i = 0; i < ele.length; i++){
if(ele[i].type == 'checkbox' && ele[i].checked){
arr.push(ele[i].value);
}
}
return arr;
}
var array = []
$("input:checkbox[name=type]:checked").each(function(){
array.push($(this).val());
});
아래 코드를 사용하여 모든 선택된 값을 가져옵니다.
var yourArray=[];
$("input[name='ordercheckbox']:checked").each(function(){
yourArray.push($(this).val());
});
console.log(yourArray);
삽입을 실행하기 위해 버튼 클릭 등을 사용하는 경우 배열에 이미 있는 값을 추가하지 않으려면 주석 첨부 if 블록을 사용합니다.
$('#myDiv').change(function() {
var values = [];
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values.push($(this).val());
// }
});
console.log(values);
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
다음과 같은 작업을 수행할 수 있습니다.
$('input[type="checkbox"]').change(function(){
var checkedValue = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
alert(checkedValue); //display selected checkbox value
})
여기서
$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function() looping on all checkbox,
여기 같은 문제에 대한 내 코드가 있습니다. 누군가 이것을 시도해 볼 수도 있습니다.
<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];
$.each($("input[name='check1']:checked"), function(){
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>
내가 만든 이 기능을 사용할 수 있다
function getCheckBoxArrayValue(nameInput){
let valores = [];
let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
checked.forEach(input => {
let valor = input?.defaultValue || input?.value;
valores.push(valor);
});
return(valores);
}
그렇게 부르면
getCheckBoxArrayValue("type");
var idsComenzi = [];
$('input:checked').each(function(){
idsComenzi.push($(this).val());
});
누군가에게 도움이 될지 모르니 제 의견을 덧붙이겠습니다.
const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);
이미 jQuery 오브젝트가 있기 때문에 다음 번에는 체크박스를 모두 선택하지 않기 때문에 jQuery의 필터 방식을 사용했습니다.그런 다음 JS 배열로 변환하고 항목의 값을 반환하도록 배열을 매핑합니다.
언급URL : https://stackoverflow.com/questions/590018/getting-all-selected-checkboxes-in-an-array
'itsource' 카테고리의 다른 글
XAMPP - 테이블 'C:\xampp\tmp\#sql3a10_4_4'에 대한 권한 문제.MAI' (0) | 2022.09.12 |
---|---|
PHP는 Python의 목록 이해 구문과 동등합니까? (0) | 2022.09.12 |
각 유형에서 가장 큰 행 선택 방법 (0) | 2022.09.12 |
원칙 2에서 엔티티를 다른 행으로 다시 저장하는 방법 (0) | 2022.09.12 |
지난달 날짜를 php로 가져오는 중 (0) | 2022.09.12 |