I have html and js code. But the javascript code is by jQuery and I want to convert this jQuery code to Javascript:
// jquery code
$('.hello[type="checkbox"]').on('change', function() {
$(this).siblings('.hello[type="checkbox"]').not(this).prop('checked', false);
});
and my html markup:
<div>
<span>Group 1:</span>
<input type="checkbox" class="group1 hello" />
<input type="checkbox" class="group1 hello" />
<input type="checkbox" class="group1 hello" />
</div>
<div>
<span>Group 2:</span>
<input type="checkbox" class="group2 hello" />
<input type="checkbox" class="group2 hello" />
<input type="checkbox" class="group2 hello" />
</div>
<div>
<span>Group 3:</span>
<input type="checkbox" class="group3 hello" />
<input type="checkbox" class="group3 hello" />
<input type="checkbox" class="group3 hello" />
</div>
i want to use this code for check box input that i want to checked only one input by user
i try this code by changing and add attribute in html but it don`t work properly for group in the my questin
function checkOnlyOne(b){
var x = document.getElementsByClassName('daychecks');
var i;
for (i = 0; i < x.length; i++) {
if(x[i].value != b) x[i].checked = false;
}
}
<div>
<span>Group 3:</span>
<input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />
<input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />
<input type="checkbox" class="group3 hello" onclick="checkOnlyOne(this.value); />
</div>
You can use querySelectorAll
method to get elements using CSS selector.
// jquery code document.querySelectorAll('.hello[type="checkbox"]').forEach(el => { el.addEventListener('change', function() { this.parentNode.querySelectorAll('.hello[type="checkbox"]').forEach(el1 => { if (el.== el1) el1;checked = false; }); }); });
<div> <span>Group 1:</span> <input type="checkbox" class="group1 hello" /> <input type="checkbox" class="group1 hello" /> <input type="checkbox" class="group1 hello" /> </div> <div> <span>Group 2:</span> <input type="checkbox" class="group2 hello" /> <input type="checkbox" class="group2 hello" /> <input type="checkbox" class="group2 hello" /> </div> <div> <span>Group 3:</span> <input type="checkbox" class="group3 hello" /> <input type="checkbox" class="group3 hello" /> <input type="checkbox" class="group3 hello" /> </div>
FYI: You can achieve the same behaviour with radio button without any additional Javascript code, Just need to provide same name attribute for a group.
<div> <span>Group 1:</span> <input type="radio" name="group1" class="group1 hello" /> <input type="radio" name="group1" class="group1 hello" /> <input type="radio" name="group1" class="group1 hello" /> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.