select checkboxes with javascript based on html-5 data attribute - javascript

This code is not working:
function autoScrub() {
checkLength = document.querySelectorAll("input[type=checkbox]");
for (var i=0; i < checkLength.length; i++) {
if (checkLength[i].attr('data-z') === 1) {
checkLength[i].checked = true;
}
}
}
Each of my checkboxes has a data-z attribute of either 1 or 0. I'd like to auto-check all of the checkboxes that have a data-z attribute of 1. The code is breaking at if (checkLength[i].attr('data-z') === 1) { as apparently I cannot read the data-attribute this way.
Apart from this the rest of the code works fine. I can use checkLength[i].checked = true; and it will check all of the checkboxes, I just can't reference its data-attribute correctly in an if statement and I'm not sure how to.
Any ideas?
Update
I screwed around with two of the solutions below and finally came up with:
function autoScrub() {
$("input:checkbox").each(function() {
if ($(this).data("z") == 0) {
$(this).prop('checked', true).trigger('change');
}
});
}
and this worked. Thank you everyone for your help!

in jQuery this is one line of code:
$('input[type="checkbox"][data-z="1"]').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="0" /><br />
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="1" /><br />
<input type="checkbox" data-z="0" /><br />
EDIT
Just noticed a comment about firing the change event:
$('input[type="checkbox"][data-z="1"]').prop('checked', true).trigger('change');
https://api.jquery.com/trigger/

DOM element nodes don't have an .attr() method. I think you're looking for .getAttribute().
if (checkLength[i].getAttribute('data-z') === "1") {
checkLength[i].checked = true;
}
Also note that your attribute values will be strings, not numbers, so you'll either need to compare to strings as in my edit above, or else compare with ==.
Since you tagged your post with the jQuery tag, I'll add that your code would look like this if you were to go that route:
$("input:checkbox").each(function() {
if ($(this).data("z") == 1)
this.checked = true;
});

if you want to use pure html5 then use HTMLElement.dataset
// el.dataset.dateOfBirth = '1960-10-03'; // set the DOB.
// 'someDataAttr' in el.dataset === false
// el.dataset.someDataAttr = 'mydata';
// 'someDataAttr' in el.dataset === true
(function autoScrub() {
var el = document.querySelectorAll("input[type=checkbox]");
for (var i=0; i < el.length; i++) {
console.log(el[i].dataset.z)
if (el[i].dataset.z === "1") {
console.log(el[i]);
el[i].checked = true;
}
}
})();
<input type=checkbox id=check-1 data-id=111111 data-user=john data-date-of-birth=2jan2010 data-z=1 />
<input type=checkbox id=check-2 data-id=222222 data-user=tambo data-date-of-birth=3feb2011 data-z=2 />
<input type=checkbox id=check-3 data-id=333333 data-user=sandra data-date-of-birth data-z=3 />
<input type=checkbox id=check-4 data-id=444444 data-user=loic data-date-of-birth=4mar2012 data-z=4 />
Note: Accessing the Data
The W3C HTML5 spec has a clear method for collecting data in
JavaScript. Notice that we don’t need the “data-” in front of our
value like with getAttribute; we just call our value name directly.
This access method meets the spec, but like many HTML5 features, it
only works in HTML5 browsers.

Related

JavaScript - Toggle "check all" checkboxes true/false

I am trying to make "toggle checkboxes" function, as below:
HTML Code:
<!-- "Check all" box -->
<input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" />
<!-- the other ones -->
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />
JavaScript:
function selectbox( eID ) {
// instead of writing the element id in the html code,
// i want to use "this.getAttribute( 'id' )"
var c = document.getElementById( eID );
// now when we've got the id of the element,
// let's get the required attribute.
var box = c.getAttribute( 'name' );
// set var i value to 0, in order to run "for i" loop
var i = 0;
for(i; i < box.length; i++) {
// now lets find if the main box (as box[0]) checked.
// if returns true (it has been checked), then check all - else -
// do not check 'em all.
if(box[0].checked == true) {
box[i].checked = true;
}
else {
box[i].checked = false;
}
}
}
I don't want any jQuery solution (even if it can be easier than pure js), so please avoid suggesting it. All I want to know is - If I'm wrong - what do you think I should do to solve this?
Thank you very much. every suggestion/tip is appreciated.
Your problem mainly seems to be that you are iterating over the checkbox name, not the checkboxes with that name.
var box = c.getAttribute( 'name' );
Now, box is equal to "check", so box[0] is "c", box[1] is "h" etc.
You need to add this:
var boxes = document.getElementsByName(box);
And then iterate over boxes.
Of course, at that point, you may want to rename your variables too.
Given the name in the variable box, you can check all boxes with the same name like this:
Array.prototype.forEach.call(document.getElementsByName(box), function(el) {
el.checked = true;
});
(Array.prototype.forEach.call is used to loop over the "fake-array" returned by getElementsByName because the NodeList class doesn't have forEach.)
I think you can further simply your code by not passing the element's ID to your function, but directly the name (selectbox(this.name)). Also note that you can access ID and name using .id and .name instead of using getAttribute.
You can make it simple.
HTML Code:
input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox(this.getAttribute('name'));" />
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />
Javascript:
function selectbox(eID) {
var checkBoxes = document.getElementsByName(eID);
for (var i = 0; i < checkBoxes .length; i++) {
if (checkBoxes[0].checked) {
checkBoxes[i].checked = true;
}
else {
checkBoxes[i].checked = false;
}
}
}

JS / JQuery - Check All Checkboxes

I have a photo gallery. Underneath each photo is a checkbox, with the ID containing a prefix of 'checkbox_', followed by the photo ID.
<input type="checkbox" id="checkbox_<%=photoID%>" name="photos">
When I check a 'selectAll' checkbox, like this one:
<input type="checkbox" id="toggleAll" name="toggleAll" onclick="toggleAll()">
I want to check/uncheck all checkboxes that have the name 'photos', so I have this function that should do that... but it doesn't:
function toggleAll() {
if (document.getElementById('toggleAll').checked == true)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500);
document.getElementByName('photos').checked = true;
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
document.getElementByName('photos').checked = false;
}
}
The rest of the function works okay, it animates the background colors of the containing DIV (#photoBlob) when the toggleALL() function is called. But, I really can't get all the checkboxes to check and I have tried so many different variations!
Can anybody see what I am doing wrong? The problem lies with these two lines:
document.getElementByName('photos').checked = true;
document.getElementByName('photos').checked = false;
Any suggestions gratefully received...
You can do like this,
don't use same name for several check boxes because the name shroud be unique. Instead of use the class.
<input type="checkbox" id="checkbox_<%=photoID%>" class="photos">
an the jquery,
$('#toggleAll').click(function(){
var checked =$(this).attr('checked');
$('.photos').attr('checked', checked);
}
$('#toggleAll').click(function(){
$(':checkbox[name="photos"]').prop('checked',this.checked);
});
Fiddle demo: http://jsfiddle.net/uNeX2/
I think you're missing an "s" in getElementByTagName. Try getElementsByTagName.
This might also work:
$("#toggleAll").click(function() {<br/>
$("input[name='photos']").attr("checked",!!$(this).attr("checked"));
});
well, since you said, you have multiple checkboxes with the name 'photos', selecting only one element by using the function getElementByName, can't be ur choice of game. Using jQuery simplifies the task your trying to do;
$("input[name=photos]").each(function(elem){
elem.checked=true;
}
or simpler;
$("input[name=photos]").attr('checked','checked');
its its js-only, youd need to select all input elements via getElementsByTagName and then filter out the ones that don't comply with having a name of 'photos'.. and then do your task.
Here is simple example using jQuery:
html
<input type="checkbox" id="all" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
js
$('#all').click(function() {
if ($(this).attr('checked') == undefined) {
$('input[name=photo]').removeAttr('checked');
}
else {
$('input[name=photo]').attr('checked', 'checked');
}
});
Code: http://jsfiddle.net/b8Y9t/3/
I would use:
$('.photos:checkbox').attr('checked','checked');
There is no function called getElementByName. Did you have a javascript-error? I think it should be getElementsByName. This returns a list with elements. That means you have to loop trough it to check all checkboxes.
BTW I think it is not correct to use a name called 'photos' for a checkbox, since a checkbox is a single object and does not display a photo itself. I would name it 'photoCheckbox' or 'cbPhoto' to clearify it is a checkbox.
var checkboxList = getElementsByName('photoCheckbox'); // returns list with checkboxes with name 'photoCheckbox'
if (checkboxList)
{
for (var i = 0; i < checkboxList.length; i++)
{
var checkbox = checkboxList[i];
checkbox.checked = false;
}
}
Thats how the getElementsByName function works. So if you would evaluate this method, you would say this is unnecessary since you are already using jQuery? I would simplify the code of the checkbox:
<input type="checkbox" onclick="toggleAll(this)" />
The new toggleAll function looks like this:
function toggleAll(checkbox)
{
if (checkbox.checked)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500); // btw why 2 animations on the same elements..?
$('input[name="photos"]').prop("checked", true);
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
$('input[name="photos"]').prop("checked", false);
}
}
// jquery check all or uncheck all
$('.checkall').click(function(){
var status = 'false';
status = $('.checkall').is(":checked");
//alert ('status is ' + status); // you should see true or false
$('.metacheckbox').each( function() {
$(this).attr('checked', status);
});
});
<input class="checkall" type="checkbox" />Check/UnCheck All
<input class="metacheckbox" type="checkbox" id='checkboxone' name="checkboxone" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxtwo' name="checkboxtwo" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxthree' name="checkboxthree" value="Y" />
this worked for me.

How to Uncheck A radio button

I have two forms, one with a radio button that users must select to edit.
[form name="A"]
<li>[input type="radio" name="BookItem" value="1" /]</li>
<li>[input type="radio" name="BookItem" value="2" /]</li>
<li>[input type="radio" name="BookItem" value="3" /]</li>
[form]<p>
After "BookItem" is selected from form (A) I call the $("#EditFormWrapper").load("callEditData.cfm? ID="+ID); function to load the second form (B)
<div id="EditFormWrapper"><div></p>
<!---// begin dynamic form generated by external file callEditData.cfm //--->
[form id="editForm" name="B"]
<ul class="hourswrapper">
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs1" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs1" /> 2 Hours PM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs2" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs2" /> 2 Hours PM</li>
</ul>
[input type="image" src="images/submit-btn.gif" id="addBTN" name="addBTN" class="buttons" alt="SubmitRrequest" /]
[input type="image" src="images/cancel-btn.gif" id="editBTNcancel" name="editBTNcancel" class="buttons" alt="Cancel Request" /]
[/form]
<!---// end dynamic form from external file //--->
I want to uncheck the radio button on form (A) when user click on cancel button (editBTNcancel) in form(B).
Here's my script:
$("#editBTNcancel").live("click", function(event){
event.preventDefault();
$("#EditFormWrapper").slideUp("fast").empty();
//$('.TOR2Hours').removeAttr('checked');
$('.TOR2Hours').attr('checked', false);
});
I hope I clearly state my problem, any suggestion would be greatly appreciated!
you can access form like so ...
var exampleForm = document.forms['form_name'];
then loop through the form
for( var i=0; i<exampleForm.length; i++ ){
alert( exampleForm[i].type );
}
you can test for checked like so ...
if( exampleForm[i].checked )
to deselect the checked radio button try ...
exampleForm[i].checked=false;
the final code would look like this ...
var exampleForm = document.forms['form_name'];
for( var i=0; i<exampleForm.length; i++ ){
if( exampleForm[i].type ) == 'radio' && exampleForm[i].checked == true ){
exampleForm[i].checked = false;
}
}
I'm not sure exactly what you want but you might try using a reset input.
<input type='reset' />
Seeing as this is pretty much the easiest DOM task there is and works in every scriptable browser, I suggest not using the jQuery methods for it:
$(".TOR2Hours")[0].checked = false;
The other thing that ocurs to me is whether your selector is correct. Did you mean to select a set of elements by class or should it be an ID selector?
Your selector is simply wrong.
If you want to uncheck the radio button from first form you should use $('input[name="BookItem"]') and not $('.TOR2Hours') :
$("#editBTNcancel").on("click", function(event){
$("#EditFormWrapper").slideUp("fast").empty();
$('input[name="BookItem"]').attr('checked', false);
});
As far as which method to use to uncheck radio buttons, The following 3 methods should all work:
$('input[name="BookItem"]').attr('checked', false);
$('input[name="BookItem"]').removeAttr('checked');
$('input[name="BookItem"]').prop('checked', false);
However, check out jQuery's docs on jQuery prop() for the difference between attr() and prop().
I just discovered a great solution to this problem.
Assuming you have two radios that need to be able to be checked/unchecked, implement this code and change what's necessary:
var gift_click = 0;
function HandleGiftClick() {
if (document.getElementById('LeftPanelContent_giftDeed2').checked == true) {
gift_click++;
memorial_click = 0;
}
if (gift_click % 2 == 0) {document.getElementById('LeftPanelContent_giftDeed2').checked = false; }
}
var memorial_click = 0;
function HandleMemorialClick() {
if (document.getElementById('LeftPanelContent_memorialDeed2').checked == true) {
memorial_click++;
gift_click = 0;
}
if (memorial_click % 2 == 0) { document.getElementById('LeftPanelContent_memorialDeed2').checked = false; }
}
:) your welcome
I use this way to solve your problem in ASP.net, check this..
radioButton.InputAttributes["show"] = "false";
string clickJs = " if(this.show =='true'){this.show ='false'; this.checked = false;}else{this.show='true'; this.checked = true;};";
radioButton.Attributes["onClick"] = clickJs;
In asp.net, you can use this way to add an attribute. And you can also to add an attribute manually to the radioButton, and do the function(clickJs) to change the ckecked attributes!!!

Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?
I am using the following code, but it always returns the count of checked checkboxes regardless of id.
function isCheckedById(id) {
alert(id);
var checked = $("input[#id=" + id + "]:checked").length;
alert(checked);
if (checked == 0) {
return false;
} else {
return true;
}
}
$('#' + id).is(":checked")
That gets if the checkbox is checked.
For an array of checkboxes with the same name you can get the list of checked ones by:
var $boxes = $('input[name=thename]:checked');
Then to loop through them and see what's checked you can do:
$boxes.each(function(){
// Do stuff here with this
});
To find how many are checked you can do:
$boxes.length;
IDs must be unique in your document, meaning that you shouldn't do this:
<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />
Instead, drop the ID, and then select them by name, or by a containing element:
<fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>
And now the jQuery:
var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector
// or, without the container:
var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;
$('#checkbox').is(':checked');
The above code returns true if the checkbox is checked or false if not.
All following methods are useful:
$('#checkbox').is(":checked")
$('#checkbox').prop('checked')
$('#checkbox')[0].checked
$('#checkbox').get(0).checked
It is recommended that DOMelement or inline "this.checked" should be avoided instead jQuery on method should be used event listener.
jQuery code to check whether the checkbox is checked or not:
if($('input[name="checkBoxName"]').is(':checked'))
{
// checked
}else
{
// unchecked
}
Alternatively:
if($('input[name="checkBoxName"]:checked'))
{
// checked
}else{
// unchecked
}
The most important concept to remember about the checked attribute is
that it does not correspond to the checked property. The attribute
actually corresponds to the defaultChecked property and should be used
only to set the initial value of the checkbox. The checked attribute
value does not change with the state of the checkbox, while the
checked property does. Therefore, the cross-browser-compatible way to
determine if a checkbox is checked is to use the property
All below methods are possible
elem.checked
$(elem).prop("checked")
$(elem).is(":checked")
This is also an idea I use frequently:
var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;
If cheked, it'll return 1; otherwise it'll return 0.
You can use this code,
if($("#checkboxId").is(':checked')){
// Code in the case checkbox is checked.
} else {
// Code in the case checkbox is NOT checked.
}
As per the jQuery documentation there are following ways to check if a checkbox is checked or not. Lets consider a checkbox for example (Check Working jsfiddle with all examples)
<input type="checkbox" name="mycheckbox" id="mycheckbox" />
<br><br>
<input type="button" id="test-with-checked" value="Test with checked" />
<input type="button" id="test-with-is" value="Test with is" />
<input type="button" id="test-with-prop" value="Test with prop" />
Example 1 - With checked
$("#test-with-checked").on("click", function(){
if(mycheckbox.checked) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Example 2 - With jQuery is, NOTE - :checked
var check;
$("#test-with-is").on("click", function(){
check = $("#mycheckbox").is(":checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Example 3 - With jQuery prop
var check;
$("#test-with-prop").on("click", function(){
check = $("#mycheckbox").prop("checked");
if(check) {
alert("Checkbox is checked.");
} else {
alert("Checkbox is unchecked.");
}
});
Check Working jsfiddle
I know the OP want jquery but in my case pure JS was the answer so if anyone like me is here and do not have jquery or do not want to use it - here is the JS answer:
document.getElementById("myCheck").checked
It returns true if the input with ID myCheck is checked and false if it is not checked.
Simple as that.
You can try this:
<script>
function checkAllCheckBox(value)
{
if($('#select_all_').is(':checked')){
$(".check_").attr ( "checked" ,"checked" );
}
else
{
$(".check_").removeAttr('checked');
}
}
</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
You can use any of the following recommended codes by jquery.
if ( elem.checked ) {};
if ( $( elem ).prop( "checked" ) ) {};
if ( $( elem ).is( ":checked" ) ) {};
You can do it simply like;
Working Fiddle
HTML
<input id="checkbox" type="checkbox" />
jQuery
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
or even simpler;
$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");
If the checkbox is checked it will return true otherwise undefined
$(document).on('click','#checkBoxId',function(){
var isChecked = $(this).is(':checked');
console.log(isChecked);
});
This code above works also on bootstrap modal. isChecked is true or flase ;
Simple Demo for checking and setting a check box.
jsfiddle!
$('.attr-value-name').click(function() {
if($(this).parent().find('input[type="checkbox"]').is(':checked'))
{
$(this).parent().find('input[type="checkbox"]').prop('checked', false);
}
else
{
$(this).parent().find('input[type="checkbox"]').prop('checked', true);
}
});
Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.
In the end
<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">
var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');
This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.
For checkbox with an id
<input id="id_input_checkbox13" type="checkbox"></input>
you can simply do
$("#id_input_checkbox13").prop('checked')
you will get true or false as return value for above syntax. You can use it in if clause as normal boolean expression.
Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!
Here are the syntaxes :
var checkbox = $('#'+id);
/* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
/* The DOM way - The fastest */
if(checkbox[0].checked == true)
alert('Checkbox is checked!!');
/* Using jQuery .prop() - The second fastest */
if(checkbox.prop('checked') == true)
alert('Checkbox is checked!!');
/* Using jQuery .is() - The slowest in the lot */
if(checkbox.is(':checked') == true)
alert('Checkbox is checked!!');
I personally prefer .prop(). Unlike .is(), It can also be used to set the value.
Something like this can help
togglecheckBoxs = function( objCheckBox ) {
var boolAllChecked = true;
if( false == objCheckBox.checked ) {
$('#checkAll').prop( 'checked',false );
} else {
$( 'input[id^="someIds_"]' ).each( function( chkboxIndex, chkbox ) {
if( false == chkbox.checked ) {
$('#checkAll').prop( 'checked',false );
boolAllChecked = false;
}
});
if( true == boolAllChecked ) {
$('#checkAll').prop( 'checked',true );
}
}
}
Try this...
$(function(){
$('body').on('click','.checkbox',function(e){
if($(this).is(':checked')){
console.log('Checked')
} else {
console.log('Unchecked')
}
})
})
Toggle checkbox checked
$("#checkall").click(function(){
$("input:checkbox").prop( 'checked',$(this).is(":checked") );
})
Using this code you can check at least one checkbox is selected or not in different checkbox groups or from multiple checkboxes.
Using this you can not require to remove IDs or dynamic IDs. This code work with the same IDs.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox21" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox22" value=ck2 /> ck2<br />
<label class="control-label col-sm-4">Check Box 3</label>
<input type="checkbox" name="checkbox3" id="checkbox31" value=ck3 /> ck3<br />
<input type="checkbox" name="checkbox3" id="checkbox32" value=ck4 /> ck4<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
if (!$('input[name=checkbox3]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
Since it's mid 2019 and jQuery sometimes takes a backseat to things like VueJS, React etc. Here's a pure vanilla Javascript onload listener option:
<script>
// Replace 'admincheckbox' both variable and ID with whatever suits.
window.onload = function() {
const admincheckbox = document.getElementById("admincheckbox");
admincheckbox.addEventListener('click', function() {
if(admincheckbox.checked){
alert('Checked');
} else {
alert('Unchecked');
}
});
}
</script>
Your question is not clear: you want to give "checkbox array id" at input and get true/false at output - in this way you will not know which checkbox was checked (as your function name suggest). So below there is my proposition of body of your isCheckedById which on input take checkbox id and on output return true/false (it's very simple but your ID should not be keyword),
this[id].checked
function isCheckedById(id) {
return this[id].checked;
}
// TEST
function check() {
console.clear()
console.log('1',isCheckedById("myCheckbox1"));
console.log('2',isCheckedById("myCheckbox2"));
console.log('3',isCheckedById("myCheckbox3"));
}
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>
You can try either any of the ways preferred, as in jQuery or JavaScript.
Get the value as below and assign to the variable then you if-else statements as per your requirement.
var getVal=$('#checkbox_id').is(":checked"); // jQuery
var getVal=document.getElementById("checkbox_id").checked //JavaScript
if (getVal==true) {
// perform task
} else {
// perform task
}
use code below
<script>
$(document).ready(function () {
$("[id$='chkSendMail']").attr("onchange", "ShowMailSection()");
}
function ShowMailSection() {
if ($("[id$='chkSendMail'][type='checkbox']:checked").length >0){
$("[id$='SecEmail']").removeClass("Hide");
}
</script>

Javascript and only one Checkbox - undefined

for (i = 0; i < document.checks.user.length; i++) //for all check boxes
{
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
<body>
<form action="" method=POST name="checks" ID="Form2">
I have a bike:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<br>
<br>
</form>
<input type="button" value="Delete"
class="btn" onclick="sub_delete()"
onmouseover="hov(this, 'btn btnhov')" onmouseout="hov(this, 'btn')"
id="Button1" name="Button1"
/>
</body>
as you probably already know when there is only one check box left document.checks.user.length = undefined. Whats the most efficient way to make sure that when there is only one check box, it will be deleted. I was thinking just thinking to add it as a seperate if statement before the if statement here.....any suggesstions.
Thanks.
Use a loop control variable, and set it to 1 if length is undefined...
var len = document.checks.user.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++) //for all check boxes
Best regards...
if (document.getElementById('Checkbox1').checked) { /* do something */ }
if you want to loop a bunch of checkboxes, you could loop the input fields of your form, like:
var formNodes = document.checks.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
}
if(document.checks.user[0]) {
//it's an array
}
else {
//it's a single element
}
Your question is somewhat confusing, since your javascript would obviously have to be inside a function called 'sub_delete' to be any use... someone with the mighty power to edit questions might improve the question by making that clearer...
So the first issue you have to get around is the fact that for single checkbox, with a given name 'user', is not an array, and therefore has no defined length, but also if you try and access it as an array.. things get confused.. a full rewrite of your javascript function might look like this:
function sub_delete{
if (typeof document.checks.user.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.checks.user.checked == true )
{
document.checks.submit();
return 0;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.checks.user.length; i < max; i++){
if (document.checks.user[i].checked == true )
{
document.checks.submit();
return 0;
}
}
}
}//sub_delete end
HTH,
-FT
I too face the same proble with total of 5 checkboxes out of which 4 are disabled and 1 is enabled. Now the checkboxId.length is undefined, so the only option I could think of is if(checkboxId.length ==undefined ){checkboxId.checked=true & submith the form}.
It's very simple, just create a hidden input tag with the name same as the existing checkbox input tag.
For example:
<input type="checkbox" name="user" value="Bike" ID="Checkbox1">
<input type="hidden" name="user" value=""/>
I'd probably iterate across document.checks.elements, looking for .type == 'checkbox'.
jQuery is your friend:
$("input[type='checkbox']").attr('checked', false);
(... if jQuery is available to you?)

Categories