I am having 100 Checkboxes on my web page. For testing purposes I want to tick all those boxes, but manually clicking is time consuming. Is there a possible way to get them ticked?
Perhaps a JavaScript or Chrome Console window, anything?
The most direct way would be to grab all your inputs, filter just the checkboxes out, and set the checked property.
var allInputs = document.getElementsByTagName("input");
for (var i = 0, max = allInputs.length; i < max; i++){
if (allInputs[i].type === 'checkbox')
allInputs[i].checked = true;
}
If you happen to be using jQuery—and I'm not saying you should start just to tick all your checkboxes for testing—you could simply do
$("input[type='checkbox']").prop("checked", true);
or as Fabricio points out:
$(":checkbox").prop("checked", true);
Pure JS method, don't use jQuery.. its just silly for something so trivial.
[].forEach.call( document.querySelectorAll('input[type="checkbox"]'),function(el){
el.checked=true;
}
);
Live Demo
To use it on any webpage you can paste this into the address bar
javascript:[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});
then drag that to your bookmarks, and you have a bookmarklet. Just click it whenever you need to use it on a page.
querySelectorAll is your best choice here if you don't want jQuery!
var ele = document.querySelectorAll("input[type=checkbox]");
for(var i=0;i<ele.length;i++){
ele[i].checked = true;
}
//Done.
by using jquery, simple as that
$('input:checkbox').each(function () {
// alert(this);
$(this).attr('checked', true);
});
Or simply use
$('input:checkbox').prop('checked', true);// use the property
OR
$('input:checkbox').attr('checked', true); // by using the attribute
Just paste one of these one-liners to your browser console:
Tick all checkboxes:
document.querySelectorAll('input[type="checkbox"]').forEach(e => e.checked = true);
Untick all checkboxes:
document.querySelectorAll('input[type="checkbox"]').forEach(e => e.checked = false);
This JS code will check all checkboxed in your page:
var a = document.querySelectorAll('input[type="checkbox"]');
for (var i=0; i<a.length; i++)
a[i].checked = true;
Live demo
All you have to do then is create a bookmarklet with it, say, with this bookmarklet maker, which generates this bookmarklet code:
javascript:var a=document.querySelectorAll('input[type="checkbox"]');for(var i=0;i<a.length;i++)a[i].checked=true;%E2%80%8B
Just add this URI to a bookmark in your bookmark toolbar, then all you have to do is click it whenever you need all the checkboxes in your page to be checked. =]
Multiple Check All & Uncheck All Boxes
All You Need to change is the tag 'name' to change the what its turing ON/OFF
<FORM>
<input type="checkbox" name="item0[]" onclick="CheckAll(this)" />
<input type="checkbox" name="item0[]" value="1" />
<input type="checkbox" name="item0[]" value="2" />
<input type="checkbox" name="item0[]" value="3" />
<br>
<input type="checkbox" name="item1[]" onclick="CheckAll(this)" />
<input type="checkbox" name="item1[]" value="a" />
<input type="checkbox" name="item1[]" value="b" />
<input type="checkbox" name="item1[]" value="c" />
<br>
<input type="checkbox" name="item2" onclick="CheckAll(this)" />
<input type="checkbox" name="item2" value="a1" />
<input type="checkbox" name="item2" value="b2" />
<input type="checkbox" name="item2" value="bc" />
</FORM>
<script>
function CheckAll(x)
{
var allInputs = document.getElementsByName(x.name);
for (var i = 0, max = allInputs.length; i < max; i++)
{
if (allInputs[i].type == 'checkbox')
if (x.checked == true)
allInputs[i].checked = true;
else
allInputs[i].checked = false;
}
}
</script>
I provided answer to this question at Check all Checkboxes in Page via Developer Tools
In short you can do it from dev tools console (F12) by:
$$('input').map(i => i.checked = true)
or
$$('input[type="checkbox"').map(i => i.checked = true)
The following code will toggle all checkboxes. I think this is useful in case you want that feature. If you check a box it will uncheck that box. I know this doesn't answer the question technically but I wanted to put it up here because it's what I use. Thanks for the comment. I hope this answer is better suited to your pallette.
//Select All Checkboxes On Page
allSelects = document.querySelectorAll('input[type="checkbox"]');
for(i=0;i<allSelects.length;i++){
allSelects[i].click();
}
function selectAll(elem)
{
for (i = 0; i < elem.length; i++)
elem[i].checked = true ;
}
On Click of a button call this method and pass the name of the element(checkboxes-they all should be same named).
Related
I was wondering if there was a better way to go about enabled/disabled multiple checkboxes at once.
In the html I have two radio buttons to choose between all hair options and custom hair options, having the default all one disable the checkboxes while the custom one enables them.
This is what I've got so far that works (probably looks dumb, I apologize), but I'd like to know if there's a more efficient way to go about this? I'd like to do it as "small" as possible while still being easily readable/understandable for my own sake.
function checkHaOp(){
if (document.getElementById("hairOptionAll").checked){
document.getElementById("hairAuburn").disabled = true;
document.getElementById("hairBlack").disabled = true;
document.getElementById("hairBlonde").disabled = true;
document.getElementById("hairBrown").disabled = true;
document.getElementById("hairRed").disabled = true;
document.getElementById("hairOther").disabled = true;
}
else if (document.getElementById("hairOptionCustom").checked){
document.getElementById("hairAuburn").disabled = false;
document.getElementById("hairBlack").disabled = false;
document.getElementById("hairBlonde").disabled = false;
document.getElementById("hairBrown").disabled = false;
document.getElementById("hairRed").disabled = false;
document.getElementById("hairOther").disabled = false;
}
}
Preferably using javascript since I don't know jquery.
I'd also appreciate explanations of things since I am still learning.
You can add/use class like said #NiettheDarkAbsol
then something like that.
var inpck = document.getElementsByClassName("input-checkbox");
if (document.getElementById("hairOptionAll").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = true;
}
}
if (document.getElementById("hairOptionCustom").checked) {
for(var i = 0; i < inpck.length; i++) {
inpck[i].disabled = false;
}
}
Now your turn to refactor this :D
You can use
document.querySelectorAll('[id^=hair]')
It selects all elements that has an id which starts with "hair"
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="hairOptionAll">
<input type="checkbox" id="hairAuburn">
<input type="checkbox" id="hairBlack">
<input type="checkbox" id="hairBlonde">
<input type="checkbox" id="hairBrown">
<input type="checkbox" id="hairRed">
<input type="checkbox" id="hairOther">
</body>
<script>
const hairCb = document.querySelectorAll('[id^=hair]');
for (let i=0; i<hairCb.length; i++) {
hairCb[i].disabled = true;
}
</script>
</html>
Here's the optimized solution.
<div class="radio-btns">
All <input type="radio" id="hairOptionAll" name="hairOptionAll"/>
Custom <input type="radio" id="hairOptionCustom" name="hairOptionCustom"/>
</div>
<div class="hairOptions">
hairAuburn <input type="checkbox" id="hairAuburn" />
hairBlack <input type="checkbox" id="hairBlack" />
hairBlonde <input type="checkbox" id="hairBlonde" />
hairBrown <input type="checkbox" id="hairBrown" />
hairRed <input type="checkbox" id="hairRed" />
hairOther <input type="checkbox" id="hairOther" />
</div>
<script type="text/javascript">
const radioBtns = document.querySelector('.radio-btns');
radioBtns.children[0].checked = true;
radioBtns.addEventListener("click", (event) => {
radioBtns.children[0].checked = (event.target.id == 'hairOptionAll') ? true : false;
radioBtns.children[1].checked = (event.target.id == 'hairOptionCustom') ? true : false;
const allOptions = [...event.target.parentElement.nextElementSibling.children];
allOptions.map(option => ( option.checked = (event.target.id == 'hairOptionCustom') ? true : false ) );
});
</script>
Here is a complete working code you. To minimise the code we write to we need to use a class selector not an id - Give the same class to your radio button and then use a forEach loop to go through all the radio button. Add the class to your checkboxes as well.
To get all the checkboxes we can use forEach method.
Once you have all the radio button you need to listen for a change on a particular radio button and then we will check whether the radio button we have selected is checked and its id is all or custom.
To get the id of the actual radio button which was clicked we can use getAttribute method which return the id of checked radio button.
If our condition matches we will disable all the checkboxes or if its else then we enable all the checkboxes using forEach loop on the checkbox classes.
We will pass true or false as an argument to disable checkboxes function to avoid having have two loops
Live Working Example (I have added notes / comment on each line of code for your understanding as well)
//Enable disable checkbox
function disableChekbox(isChecked) {
let getHairOptions = document.querySelectorAll('.hairOptions') //get all checkboxes
getHairOptions.forEach(function(x) {
x.disabled = isChecked
})
}
let getHairRadio = document.querySelectorAll('.hairOptionAll') //get all radio buttons
//For each all radio buttons
getHairRadio.forEach(function(radio) {
//listen to change on radio
radio.addEventListener('change', function(e) {
if (e.target.checked && e.target.getAttribute('id') == 'hairOptionAll') {
//loop through all checkboxes
disableChekbox(true)
} else if (e.target.checked && e.target.getAttribute('id') == 'hairOptionCustom') {
//loop through all checkboxes
disableChekbox(false)
}
})
})
All <input type="radio" id="hairOptionAll" name="hairOptionAll" class="hairOptionAll" />
Custom <input type="radio" id="hairOptionCustom" name="hairOptionAll" class="hairOptionAll" />
<br>
<br>
hairAuburn <input type="checkbox" id="hairAuburn" class="hairOptions" />
hairBlack <input type="checkbox" id="hairBlack" class="hairOptions" />
hairBlonde <input type="checkbox" id="hairBlonde" class="hairOptions" />
hairBrown <input type="checkbox" id="hairBrown" class="hairOptions" />
hairRed <input type="checkbox" id="hairRed" class="hairOptions" />
hairOther <input type="checkbox" id="hairOther" class="hairOptions" />
I've searched all the web about it but i couldn't find a solution in javascript without jquery. The problem is the following: I have an entire array of radio elements, which should be checked or unchecked depending on database data. And this is accomplished. Now i have to make the radio button "uncheckable" to change the database data through the form.
I tried to make it in plain javascript as i don't want to think about frontend libraries for the moment.
The html is the following:
<td>
<input class="graphs" name="g4" value="S" defaultvalue="N" checked="true" type="radio">
</td>
<td>
<input class="graphs" name="g5" value="S" defaultvalue="N" type="radio">
The Javascript is the following:
<script type="text/javascript">
window.onload = (function(){
return function(){
var allRadios = document.getElementsByClassName('graphs');
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(this.checked == true){
this.checked = false;
}else{
this.checked = true
}
};
}
}})();
</script>
I've tried to debug and the result is always the same: the first if is executed and always true, even when the element is not checked.
I've tried the same script in jsfiddle and it works right. Is it a problem of my browser?
Thanks in advance.
this.checked == true in else block is not an assignment
If you want a radio to be uncheckable the you can disable it statically, you don't need to use any javascript.
For Unckecked disabled
<input type="radio" name="foo" value="N" disabled>
Four Checked disabled
<input type="radio" name="foo" value="N" checked disabled>
I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)
What method would be best to use to selectively set a single or multiple radio button(s) to a desired setting with JavaScript?
Very simple
radiobtn = document.getElementById("theid");
radiobtn.checked = true;
the form
<form name="teenageMutant">
<input value="aa" type="radio" name="ninjaTurtles"/>
<input value="bb" type="radio" name="ninjaTurtles"/>
<input value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" will be checked by default, if you remove the "checked" non of the boxes will be checked when the form is first loaded.
document.teenageMutant.ninjaTurtles[0].checked=true;
now value="aa" is checked. The other radio check boxes are unchecked.
see it in action: http://jsfiddle.net/yaArr/
You may do the same using the form id and the radio button id. Here is a form with id's.
<form id="lizardPeople" name="teenageMutant">
<input id="dinosaurs" value="aa" type="radio" name="ninjaTurtles"/>
<input id="elephant" value="bb" type="radio" name="ninjaTurtles"/>
<input id="dodoBird" value="cc" type="radio" name="ninjaTurtles" checked/>
</form>
value="cc" is checked by default.
document.forms["lizardPeople"]["dinosaurs"].checked=true;
now value="aa" with id="dinosaurs" is checked, just like before.
See it in action: http://jsfiddle.net/jPfXS/
Vanilla Javascript:
yourRadioButton.checked = true;
jQuery:
$('input[name=foo]').prop('checked', true);
or
$("input:checkbox").val() == "true"
You can also explicitly set value of radio button:
<form name="gendersForm">
<input type="radio" name="gender" value="M" /> Man
<input type="radio" name="gender" value="F" /> Woman
</form>
with the following script:
document.gendersForm.gender.value="F";
and corresponding radio button will be checked automatically.
Look at the example on JSFiddle.
/**
* setCheckedValueOfRadioButtonGroup
* #param {html input type=radio} vRadioObj
* #param {the radiobutton with this value will be checked} vValue
*/
function setCheckedValueOfRadioButtonGroup(vRadioObj, vValue) {
var radios = document.getElementsByName(vRadioObj.name);
for (var j = 0; j < radios.length; j++) {
if (radios[j].value == vValue) {
radios[j].checked = true;
break;
}
}
}
Try
myRadio.checked=true
<input type="radio" id="myRadio">My radio<br>
$("#id_of_radiobutton").prop("checked", true);
I am configuring a radio button within a document fragment and tried using radiobtn.checked = true;.
That didn't work so I instead went with this solution:
radiobtn.setAttribute("checked", "checked");
This sets checked using name to cycle through the elements and a value check to set the desired element to true. I kept it as simple as possible, its pretty easy to put it into a function or a loop, etc.
variable 'nameValue' is the radio elements name value
variable 'value' when matched sets the radio button
Array.from( document.querySelectorAll('[name="' + nameValue + '"]') ).forEach((element,index) =>
{
if (value === element.value) {
element.checked = true;
} else {
element.checked = false;
}
});
I am using this javascript code. and on button click I want that atleast one checkbox selection is required. do anyone have idea what I am doing wrong. I don't want to use jquery.
function check()
{
var flag = false;
for(var i=1;i<=4;i++)
{
var checkb = document.getElementById("check"+i);
if(checkb.checked)
{
flag = true;
break;
}
}
if(!flag)
alert("What is your interest \n(select at least one option)");
return flag;
}
</script>
Button Click Code is
<input type="submit" name="submit" value="Submit" onclick="return check();">
The code works fine. Do hou have id="check1" set on your checkbox tags?
Yes, your code works fine as noted by the comments above. However, you could do your check for...checks a little more cleanly - you're expecting "check0" - "check4" for the IDs. You could just grab them all and not worry about a set limit (odds are your code isn't working because at least one of the IDs you're using doesn't exist).
<input type="checkbox" id="check0" />
<input type="checkbox" id="check1" />
<input type="checkbox" id="check2" />
<input type="checkbox" id="check3" />
<hr/>
<input type="button" onclick="checkIt();" value="Check the Checks">
And some JS:
checkIt = function()
{
var checks = document.getElementsByTagName('input');
var hasCheck = false;
for(i in checks)
{
// Could also check for a classname here to narrow
// your result set.
if(checks[i].type == 'checkbox')
hasCheck |= checks[i].checked;
}
if(!hasCheck)
alert('You should check one!');
return hasCheck;
}