Как пункты обернуть в input type='checkbox', чтобы все работало?
Вообще не понимаю, как правильно все элементы обернуть в чекбоксы и написать перехват кликов на них, подсчитывая количество выбранных(именно на js).
<form name="selectForm">
<p>
<label for="list">Выберите строчки:</label>
<select type = 'checkbox' id="list" name="line" multiple>
<option value='A' selected>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
<option value='D'>D</option>
<option value='E'>E</option>
</i>
</select>
<p> <input id="btn" type="button" value="Сколько выбрано?" /></p>
</form>
<script>
function Quantiny(selectLine) {
var numberSelected = 0;
for (var i = 0; i < selectLine.options.length; i++) {
if (selectLine.options[i].selected) {
numberSelected++;
}
}
return numberSelected;
}
var btn = document.getElementById("btn");
btn.addEventListener("click", function(){
alert('Выбрано элементов: ' + Quantiny(document.selectForm.list))
});
</script>
Ответы (1 шт):
Автор решения: StillR
→ Ссылка
<form id="form" name="selectForm">
<legend for="list">Выберите строчки:</legend>
<div class="form-item">
<input type="checkbox" id="a" name="a" checked>
<label for="a">A</label>
</div>
<div class="form-item">
<input type="checkbox" id="b" name="b">
<label for="b">B</label>
</div>
<div class="form-item">
<input type="checkbox" id="c" name="c">
<label for="c">C</label>
</div>
<div class="form-item">
<input type="checkbox" id="d" name="d">
<label for="d">D</label>
</div>
<div class="form-item">
<input type="checkbox" id="e" name="e">
<label for="e">E</label>
</div>
<div class="form-item">
<button id="btn" type="button">Сколько выбрано?</button>
</div>
</form>
<script>
function Quantiny() {
let inputsNode = document.querySelectorAll('#form>.form-item>input[type="checkbox"]:checked');
console.log(`Кол-во выбранных: ${inputsNode.length}`)
}
const btn = document.getElementById('btn');
btn.addEventListener('click', Quantiny);
</script>