show/hide drop down - javascript

here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script type="text/javascript">
document.getElementById("radio1").onchange = function() {
if(this.checked == true) {
document.getElementById("list1").style.visibility = "hidden";
document.getElementById("list1").style.display = "none";
}
};
document.getElementById("radio2").onchange = function() {
if(this.checked == true) {
document.getElementById("list1").style.visibility = "visible";
document.getElementById("list1").style.display = "block";
}
};
</script>
</HEAD>
<BODY>
<form method = "post">
<br /><p id="first"><label>First Name:</label><input type="text" name="first" size="30" /></p>
<br /><p id="last"><label>Last Name:</label><input type="text" name="last" size="30" /></p>
<br /><p id="instructor"><label>Instructor:</label><select name="instructor">
<option value="instructor1">instructor1</option>
<option value="instructor2">instructor2</option></select></p>
<br /><p id="hospitalorientation"><label>Hospital Orientation:</label>
<div id='buttons'>
<label><input id="radio1" type="radio" name="hospital" /> Not Complete </label>
<label><input id="radio2" type="radio" name="hospital" /> Complete </label>
</div>
<div id="list1" style="display: none;">
<label>Month Complete:
<select>
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</label>
</div>
</form>
</BODY>
</HTML>
I will have more fields like the hospital field, so i will need to do it more than one. I need a drop down to show when a certain radio button is selected. But everything i try in javascript doesnt work. I am new to javascript.

I think its because the code is executed BEFORE the list is actually added to the document structure.
Encapsulate it in a window.onload handler like this:
...
<script type="text/javascript">
window.onload=function()
{
document.getElementById("radio1").onchange = function()
{
if(this.checked == true)
{
document.getElementById("list1").style.visibility = "hidden";
document.getElementById("list1").style.display = "none";
}
};
document.getElementById("radio2").onchange = function()
{
if(this.checked == true)
{
document.getElementById("list1").style.visibility = "visible";
document.getElementById("list1").style.display = "block";
}
};
}
</script>
...
Lg
warappa

Your biggest issue here is that the javascript is going to execute prior to the radio buttons being created. Therefore document.getElementById(...) is not going to find the element, as it doesn't exist. Try adding your code to a function and having that function run onload of the body.

as a side issue you dont need the style.visibility... line
one more thing:
Typically, its better to add event listeners using the attachEvent or addEventListener methods (allows more control, and multiple listeners for one action) like this:
function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
}
else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
}
else {
el['on' + eType] = fn;
}
}
and then just use
addEvent(
document.getElementById("radio1"),
"change",
function(){
if(this.checked == true){
document.getElementById("list1").style.display = "none";
}
},
false);
This is both cross-browser and better practice

You have to wait until your object (radio button load) Here is some code that works. Or call the window.onload
<script type="text/javascript">
function checkEm() {
if (document.getElementById("radio1").checked) {
document.getElementById("list1").style.visibility = "hidden";
document.getElementById("list1").style.display = "none";
};
if (document.getElementById("radio2").checked) {
document.getElementById("list1").style.visibility = "visible";
document.getElementById("list1").style.display = "block";
};
};
</script>
<label><input id="radio1" type="radio" name="hospital" onclick="checkEm()" /> Not Complete </label>
<label><input id="radio2" type="radio" name="hospital" onclick="checkEm()" /> Complete </label>

Related

If I check 2 input radio the disabled Submit button enables, but if I uncheck them...the Submit button doesn't disable back

I just need a little help with this code.
var prv3;
var markIt3 = function(e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
};
$(function() {
$('input.class_x').on('click', markIt3);
});
$('input[type=radio]').on('change', function() {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled = true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}).change();
My request is the following:
can anybody just FIX what is missing in order for the form Submit button to go back to be disabled as it is supposed to be, because this form only enables it when 2 input type radio have been checked?
This form previous description is the main idea of everything:
A form, with several input type radios. Check at least 2 and the Submit button enables. But if you uncheck any of them, the Submit button should disable back, but I cannot manage to achieve this PART.
I just need a little HELP with IT, nothing else.
Please, DON'T change my code too much!Can it be done?
Check the fiddle right here: https://jsfiddle.net/Suiberu/70tkgk5t/13/
Thanks!
Actually problem is deselecting radio button not detected as a change. How about this
var prv3;
var markIt3 = function(e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
checkIfValid();
};
$(function() {
$('input.class_x').on('click', markIt3);
});
function checkIfValid() {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled = true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
};
input {
display: block;
margin: 0.5em 0;
}
input[type='submit']:disabled {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" autocomplete="off" method="post">
<input class="class_x" type="radio" name="name_1" value="value_1" id="id_1" />
<input class="class_x" type="radio" name="name_2" value="value_2" id="id_2" />
<input class="class_x" type="radio" name="name_3" value="value_3" id="id_3" />
<input type="submit" name="name_submit" value="OK" class="class_submit" id="SubmitButton" required/>
</form>
Or you can change the type of your inputs to checkBoxes and it will simply do the magic.
Here is the JSFiddle link.
var prv3;
var markIt3 = function (e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
};
$(function () {
$('input.class_x').on('click', markIt3);
});
$('input[type=checkbox]').on('change', function () {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled=true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}).change();
input {
display: block;
margin: 0.5em 0;
}
input[type='submit']:disabled {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" autocomplete="off" method="post">
<input class="class_x" type="checkbox" name="name_1" value="value_1" id="id_1" />
<input class="class_x" type="checkbox" name="name_2" value="value_2" id="id_2" />
<input class="class_x" type="checkbox" name="name_3" value="value_3" id="id_3" />
<input type="submit" name="name_submit" value="OK" class="class_submit" id="SubmitButton" required />
</form>
Only the type has been changed from radio button to checkbox.
this.checked = false
..does not fire the change event, so the change code doesn't get fired when a radio button is unchecked.
Add the following line of code after that line:
$(this).change();
That will fire the change code.
Try using .prop() function instead
$('input[type=radio]').on('change', function() {
var current = $('input.class_x').filter(':checked');
var $sbmtBtn = $('#SubmitButton');
$sbmtBtn.prop('disabled', true);
if (current.length > 1) {
$sbmtBtn.prop('disabled', false);
} else {
$sbmtBtn.prop('disabled', true);
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" class="class_x">
<input type="radio" class="class_x">
<input id="SubmitButton" type="submit">
</form>
.prop() documentation

Checkbox treeview functionality is not working

This is below code is not working as expected. I mean, on this treeview, when I press the last 4 checkboxs, then, the first checkbox should be checked automatically. Whenever the sublevel checkbox['checkboxG2'] count comes to 4, then, the first level['checkboxG1'] should be selected automatically. Any help please?
<html>
<head></head>
<body>
<div id="BuCheck" class="BusinessCont">
<p><input type="checkbox" name="checkboxG1" id="checkbox1" class="form-checkbox" value="Trauva"/><label for="checkbox1" class="form-label">Trauva</label></p>
<p>   <input type="checkbox" name="checkboxG2" id="checkbox2" class="form-checkbox" value="Nitro"/><label for="checkbox2" class="form-label">Nitro</label></p>
<p>   <input type="checkbox" name="checkboxG2" id="checkbox3" class="form-checkbox" value="Global Market"/><label for="checkbox3" class="form-label">Global Market</label></p>
<p>   <input type="checkbox" name="checkboxG2" id="checkbox4" class="form-checkbox" value="Government Services"/><label for="checkbox4" class="form-label">Government Services</label></p>
<p>   <input type="checkbox" name="checkboxG2" id="checkbox5" class="form-checkbox" value="PHASIZE"/><label for="checkbox5" class="form-label">PHASIZE</label></p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var checkBoxBusiness = function(){
console.log("Checkbox button clickes");
var myChekall = $("#BuCheck input[name=checkboxG2]"), myChecksin = $("#BuCheck input[name=checkboxG1]")[0], myCheckedAll=$("#BuCheck input[name=checkboxG2]:checked");
console.log(myCheckedAll.length);
if(myChekall.length == myCheckedAll.length) {
$(myChecksin).attr("checked", "true");
}
}
checkBoxBusiness();
</script>
</body>
</html>
Try to change this part
checkBoxBusiness();
to
$("#BuCheck input[name=checkboxG2]").on('change', checkBoxBusiness);
See fiddle.
EDIT:
I've been modified my code. Now it can uncheck main checkbox when all sublevel checkboxes are unchecked:
var checkBoxBusiness = function(){
console.log("Checkbox button clickes");
var myChekall = $("#BuCheck input[name=checkboxG2]"),
myChecksin = $("#BuCheck input[name=checkboxG1]"),
myCheckedAll=$("#BuCheck input[name=checkboxG2]:checked");
console.log(myCheckedAll.length);
if(myChekall.length == myCheckedAll.length) {
myChecksin.prop('checked', true);
} else if(!myCheckedAll.length) {
myChecksin.prop('checked', false);
}
}
$("#BuCheck input[name=checkboxG2]").on('change', checkBoxBusiness);
New demo.
If you want another option here you go:
$(document).ready(function () {
$("[name='checkboxG2']").on("click", function () {
if ($("[name='checkboxG2']:checked").length == 4) {
$("[name='checkboxG1']").prop('checked', true);
}
})
})
Example: http://jsfiddle.net/af8h9e6r/1/

Show DIV dynamically when clicking on Radio Selection

I have been supplied with this code that I can't seem to get working, I've looked around previous questions but can't find anything exactly like it. Maybe it's just totally wrong and should just start again?
What I want to do is show a div when a radio button is selected. Here is my code:
<script type="text/javascript">
jQuery(document).ready(function($){
$('input[name="item_meta[478]"]').change(function(){
var val1 = $("input[name='item_meta[478]']:checked").val();
if (val1== "España") {
document.getElementById("div1").style.display = "block";
document.getElementById("div2").style.display = "none";
}
if (val1== "Intracomunitario") {
document.getElementById("div2").style.display = "block";
document.getElementById("div1").style.display = "none";
}
}
</script>
<form>
Show form?
<input type="radio" onclick="frmCheckDependent(this.value,'478')" checked="checked" value="España" id="field_478-0" name="item_meta[478]">España
<input id="field_478-1" type="radio" onclick="frmCheckDependent(this.value,'478')" value="Intracomunitario" name="item_meta[478]">Intracomunitario
</form>
<div id="div1" style="display:none">
Custom form España
</div>
<div id="div2" style="display:none">
Custom form Intracomunitario
</div>
Thanks a lot !
A programmer told me I could do what I want to do with:
<script type="text/javascript">
jQuery(document).ready(function($){
$('input[name="item_meta[988]"], input[name="item_meta[989]"]').change(function(){
var val1 = $("input[name='item_meta[988]']:checked").val();
var val2 = $("input[name='item_meta[989]']:checked").val();
if (val1 !=undefined && val2 != undefined)
{$("#field_keytotal").val(val1+' '+val2);}
});
});
</script>
And:
<form>
Show form?
<input type="radio" id="showform" value="yes" name="showform" onchange="showhideForm(this.value);"/>Yes
<input type="radio" id="showform" value="no" name="showform" onchange="showhideForm(this.value);"/>No
</form>
<script type="text/javascript">
function showhideForm(showform) {
if (showform == "yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
if (showform == "no") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
}
}
</script>
<div id="div1" style="display:none">
[formidable id=18]
</div>
<div id="div2" style="display:none">
You are not qualified to see this form.
</div>
jsfiddle.net/cvn6n/72
You're missing a closing bracket. Add one before the </script>

Clear contents on click

In the following code:
<INPUT TYPE="radio" name="1" id="1" VALUE="1" <?php echo $checked1 ?>><font size="2">1</font>
<INPUT TYPE="radio" name="2" id="2" VALUE="2" <?php echo $checked2 ?>><font size="2">2</font>
<TEXTAREA name="names" id="names" rows="15" cols="65"><?php echo $names ?></TEXTAREA>
If the radio button 1 selected for the first time then onclick on textarea its contents should be cleared, but if the user clicks for the second time on the same text area the contents should not be cleared for the same radio button1.
The same should hold good for radio button2. How is this done?
This will fullfill your requirement. just place in body tag
<input type="radio" name="G1" id="1" value="1" /> <font size="2">1</font>
<input type="radio" name="G1" id="2" value="2" /> <font size="2">2</font>
<textarea name="names" id="names" rows="15" cols="65" onfocus="handleOnFocus()"></textarea>
<script type="text/javascript">
var isCleardForButton1 = false;
var isCleardForButton2 = false;
function handleOnFocus() {
var objTA = document.getElementById("names");
var objRadio1 = document.getElementById("1");
var objRadio2 = document.getElementById("2");
if (isCleardForButton1 == false && objRadio1.checked == true) {
objTA.value = "";
isCleardForButton1 = true;
}
if (isCleardForButton2 == false && objRadio2.checked == true) {
objTA.value = "";
isCleardForButton2 = true;
}
}
</script>
Demo and here is the code:
<TEXTAREA name="names" id="names" rows="15" cols="65" onclick="doIt(this);">Hello There</textarea>
<script>
var isDone = false;
function doIt(field)
{
if (document.getElementById("1").checked == true && isDone == false)
{
field.value = "";
isDone = true;
}
}
</script>
This would clear contents for the first time and not again for the life time of page.
edit: Looks like I mis-understood your requirements. This only applies to the click of the radio button, not to the textarea.
You need to setup a click event to clear the textarea content, and then unbind itself.
With jQuery the event handler would be something like:
$('#names').val('');
$(this).unbind('click');

How to implement "select all" check box in HTML?

I have an HTML page with multiple checkboxes.
I need one more checkbox by the name "select all". When I select this checkbox all checkboxes in the HTML page must be selected. How can I do this?
<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/>
UPDATE:
The for each...in construct doesn't seem to work, at least in this case, in Safari 5 or Chrome 5. This code should work in all browsers:
function toggle(source) {
checkboxes = document.getElementsByName('foo');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
Using 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;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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" />
I'm not sure anyone hasn't answered in this way (using jQuery):
$( '#container .toggle-button' ).click( function () {
$( '#container input[type="checkbox"]' ).prop('checked', this.checked)
})
It's clean, has no loops or if/else clauses and works as a charm.
I'm surprised no one mentioned document.querySelectorAll(). Pure JavaScript solution, works in 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 />
here's a different way less code
$(function () {
$('#select-all').click(function (event) {
var selected = this.checked;
// Iterate each checkbox
$(':checkbox').each(function () { this.checked = selected; });
});
});
Demo http://jsfiddle.net/H37cb/
<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>
When you call document.getElementsByName("name"), you will get a Object. Use .item(index) to traverse all items of a 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/​">​
Slightly changed version which checks and unchecks respectfully
$('#select-all').click(function(event) {
var $that = $(this);
$(':checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
My simple solution allows to selectively select/deselect all checkboxes in a given portion of the form, while using different names for each checkbox, so that they can be easily recognized after the form is POSTed.
Javascript:
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 example:
<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>
I hope you like it!
<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>
Try this simple JQuery:
$('#select-all').click(function(event) {
if (this.checked) {
$(':checkbox').prop('checked', true);
} else {
$(':checkbox').prop('checked', false);
}
});
JavaScript is your best bet. The link below gives an example using buttons to de/select all. You could try to adapt it to use a check box, just use you 'select all' check box' onClick attribute.
Javascript Function to Check or Uncheck all Checkboxes
This page has a simpler example
http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html
This sample works with native JavaScript where the checkbox variable name varies, i.e. not all "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>
It's rather simple:
const selectAllCheckboxes = () => {
const checkboxes = document.querySelectorAll('input[type=checkbox]');
checkboxes.forEach((cb) => { cb.checked = true; });
}
If adopting the top answer for jQuery, remember that the object passed to the click function is an EventHandler, not the original checkbox object. Therefore code should be modified as follows.
HTML
<input type="checkbox" name="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/>
Javascript
$(function() {
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>
that should do the job done:
$(':checkbox').each(function() {
this.checked = true;
});
You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName
The Select All button
<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All
Some of the checkboxes to select
<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' />
The javascript
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;
}
}
This is what this will do, for instance if you have 5 checkboxes, and you click check all,it check all, now if you uncheck all the checkbox probably by clicking each 5 checkboxs, by the time you uncheck the last checkbox, the select all checkbox also gets unchecked
$("#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)
}
})
As I cannot comment, here as answer:
I would write Can Berk Güder's solution in a more general way,
so you may reuse the function for other checkboxes
<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/>
$(document).ready(function() {
$(document).on(' change', 'input[name="check_all"]', function() {
$('.cb').prop("checked", this.checked);
});
});
Using jQuery and knockout:
With this binding main checkbox stays in sync with underliying checkboxes, it will be unchecked unless all checkboxes checked.
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();
}
};
in 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"/>
to make it in short-hand version by using jQuery
The select all checkbox
<input type="checkbox" id="chkSelectAll">
The children checkbox
<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);
})
Below methods are very Easy to understand and you can implement existing forms in minutes
With Jquery,
$(document).ready(function() {
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
$('#uncheck-all').click(function(){
$("input:checkbox").attr('checked', false);
});
});
in HTML form put below buttons
<a id="check-all" href="javascript:void(0);">check all</a>
<a id="uncheck-all" href="javascript:void(0);">uncheck all</a>
With just using javascript,
<script type="text/javascript">
function checkAll(formname, checktoggle)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = checktoggle;
}
}
}
</script>
in HTML form put below buttons
<button onclick="javascript:checkAll('form3', true);" href="javascript:void();">check all</button>
<button onclick="javascript:checkAll('form3', false);" href="javascript:void();">uncheck all</button>
Here is a backbone.js implementation:
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
javascript
$(':checkbox.all').change(function(){
$(':checkbox.item').prop('checked', this.checked);
});
1: Add the onchange event Handler
<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>
2: Modify the code to handle checked/unchecked
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;
}
}
}
}
You can Use This code.
var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
let checkboxes = document.querySelectorAll(".dlMultiDelete");
checkboxes.forEach(function (ele) {
ele.checked = !!checkbox.checked;
});
});
You can use this simple code
$('.checkall').click(function(){
var checked = $(this).prop('checked');
$('.checkme').prop('checked', checked);
});
Maybe a bit late, but when dealing with a check all checkbox, I believe you should also handle the scenario for when you have the check all checkbox checked, and then unchecking one of the checkboxes below.
In that case it should automatically uncheck the check all checkbox.
Also when manually checking all the checkboxes, you should end up with the check all checkbox being automatically checked.
You need two event handlers, one for the check all box, and one for when clicking any of the single boxes below.
// 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"));
}

Categories