Why my logic is wrong? Checkbox and line-through - javascript

I am a newbie in JS. Just want help to figure out why my logic is wrong, when I try to change the style of the text when the checkbox.checked === true.
Here is the code.
JS:
var c = document.getElementById("cbx");
var l = document.getElementById("cbxtxt");
if ( c.checked === true ) {
l.style.textDecoration = "line-through";
}
HTML:
<html>
<head></head>
<body>
<input type="checkbox" id="cbx">
<label for="cbx" id="cbxtxt">Shaneningans</label>
//<script type="text/javascript" src="cbx_test.js"></script>
</body>
</html>
Thanks in advance!

You need to wrap your logic in an event listener so that it runs every time the checkbox is checked / unchechecked. Also, you probably want to handle what happens when the checkbox is unchecked.
var c = document.getElementById("cbx"); // for checbox
var l = document.getElementById("cbxtxt"); // for label
c.addEventListener("change", function() {
l.style.textDecoration = c.checked ? "line-through" : "none";
})
<input type="checkbox" id="cbx">
<label for="cbx" id="cbxtxt">Shaneningans</label>
To explain this line:
l.style.textDecoration = c.checked ? "line-through" : "none"
As others have said c.checked === true isn't really necessary, as you can just directly use c.checked as your condition. To make the code a bit more concise, I use the conditional operator (?:) instead of a an if / else.
Finally, just to demonstrate how #A. Wolff's suggestion of using pure CSS would work:
#cbx:checked~label {
text-decoration: line-through;
}
<input type="checkbox" id="cbx">
<label for="cbx" id="cbxtxt">Shaneningans</label>

You need to subscribe to checkbox's change event, otherwise your code only runs once when the <script> element is parsed.
Consider this:
var c = document.getElementById("cbx"); // for checbox
var l = document.getElementById("cbxtxt"); // for label
c.addEventListener('change', function(evt) {
//this anonymous function will run each time the checkbox changes state
if (c.checked === true) {
l.style.textDecoration = "line-through";
} else {
l.style.textDecoration = "";
}
});

you need to add event listener
var l = document.getElementById("cbxtxt"); // for label
var c = document.getElementById("cbx"); // for checbox
c.addEventListener('change', (event) => {
if (event.target.checked) {
console.log('checked')
l.style.textDecoration = "line-through";
} else {
console.log('not checked')
l.style.textDecoration = "blink";
}
})

You would rather use classes instead of id attributes.
I guess you'll need to display different checkboxes, that in your case must have different ids (the same id is not recommended on the page).
That's why you can use my snippet to figure out how to work with multiple checkboxes.
var checkboxes = document.querySelectorAll(".my-form .my-custom-checkbox-class"); // Search all checkboxes in the form
for (var checkBox of checkboxes) {
checkBox.addEventListener("change", onCheckboxChangeHandler, false); // Add event listener to each checkbox
}
function onCheckboxChangeHandler(e) {
var clickedCheckbox = this
var formGroupContainer = clickedCheckbox.closest('.form-group'); // Find closest parent element with class .form-group
var label = formGroupContainer.querySelector('.my-custom-lbl-class'); // Find label closest to clicked checkbox
label.style.textDecoration = clickedCheckbox.checked ? "line-through" : "none"; //Do everything you need with styles
}
.my-form {
padding: 20px;
}
.form-group {
padding: 5px 10px;
font-size: 18px;
}
<div class="my-form">
<div class="form-group">
<input type="checkbox" id="cb1" class="my-custom-checkbox-class">
<label for="cb1" class="my-custom-lbl-class">Waterfall</label>
</div>
<div class="form-group">
<input type="checkbox" id="cb2" class="my-custom-checkbox-class">
<label for="cb2" class="my-custom-lbl-class">River</label>
</div>
</div>

Related

Reveal additional info based on two (out of three) checkboxes JavaScript

I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');

Disable CheckBox Dynamically using JQuery

I have a collection of checkboxes within a form. I am looping through the collection to check and/or disable the checkboxes. The checking works fine; however, I am having an issue with checking if the checkbox is disabled or not. It always return false even when the checkbox is enabled. I looked at the code over and over, and I could not see a anything that could cause this to happen.
Partial HTML File
<label class="col-lg-3"><div style="padding-left:5px;">View Department</div></label>
<div class="col-lg-1"><input id="Accounting" name="Accounting" type="checkbox" /> </div>
<label class="col-lg-3"> Finance</label>
<div class="col-lg-1"><input id="Finance" name="Finance" type="checkbox" /></div>
<label class="col-lg-3"> Marketing</label>
<div class="col-lg-1"><input id="Marketing" name="Marketing" type="checkbox" /></div>
<div class="col-lg-12">
<hr style="width:100%;" />
</div>
//This is how I disable the checkbox
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
if (typeof (e) !== 'undefined') {
if (e) {
switch (e) {
case 'Education':
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id == 'Accounting') || (collection[i].id == 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
break;
}
}
}
//The rendering HTML
<input checked="checked" id="Accounting" name="Accounting" type="checkbox" disabled>
//checking if the field is disabled or not
var isAccountingDisabled = $('#Accounting').is(':disabled');
//The above code always return false. Why is that?
I added a screen shot of the checkbox property showing that the checkbox is automatically checked and disabled. Even though the checkbox is rendering as disabled, the property does not show it as being disabled.
You can't have multiple elements with the same id. In your looping structure you can add the index of the loop also to the id, so that it will be unique. (Accounting1, Accounting2...)
Change your code to something like this
var checkBoxesCollection = $("#yourparentelement").find("input:checkbox[name='Accounting']");
$.each(checkBoxesCollection, function(){
if (this.disabled) {
};
});
http://jsfiddle.net/eanamztz/
Use === instead of ==
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id === 'Accounting') || (collection[i].id === 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
I was not able to read the property using $('#Accounting').is(':checked'); however, I was able to read them using the syntax below.
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
$.each(collection, function (index, item) {
ListDepartments[item.name + "Disabled"] = item.disabled;
})

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Only one checkbox selected

I have a checkbox Yes and No so i want to user only able to use one. So if user tick Yes then No will cleared if Yes then no will clear
<input type="checkbox" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "Yes" ? " checked" : "")/>Yes
<input type="checkbox" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "No" ? " checked" : "")/>No
<script>
function selectOnlyThis(id) {
for (var i = 0; i <= 4; i++) {
document.getElementById("Check" + i).checked = false;
}
document.getElementById(id).checked = true;
}
</script>
The problem is that you are trying to access elements that do not exist
your loop goes from 0 to 4 but your elements are Check1 and Check2
So when it tries to set the checked property of Check0 (which does not exist) it throws an error and stops execution..
Use
function selectOnlyThis(id) {
console.log(id);
for (var i = 0; i <= 4; i++) {
var element = document.getElementById("Check" + i); // get element
if (element){ // if element was found only the set its checked property
document.getElementById("Check" + i).checked = false;
}
}
document.getElementById(id).checked = true;
}
Demo at http://jsfiddle.net/gaby/RHUVf/
or if your example html is the actual one you could just change your loop to
for (var i = 1; i <= 2; i++) {
As mentioned by others, you are describing the behavior of a radio button. However, it is possible to make a checkbox behave like this also.
jsFiddle demo
$('input:checkbox').click(function(){
$('input:checkbox').not($(this)).prop('checked',false);
});
The above code does the following:
$('input:checkbox') - selects all input elements of type checkbox
.not($(this)) - except this one
.prop('checked',false) - unchecks the checkbox
This code uses the jQuery javascript library, so you must reference this library (usually in the head tags of the document), thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
It would be a lot more helpful/easier to use HTML5 for this part
IF you choose HTML5 the following code WILL work but if you decide not to use it It wont help.
<input type="checkbox" name="<name>" value="<value"><*explanation*><br/><br/>
</form>
</div>
</div>
</body>

too see if checkboxes have been checked javascript

Hallo
How would I go about in checking whether checkBox has been checked in javascript?
I C# it is simple enough
int selected = 0;
for (int loop = 0; loop < chkMeal.CheckedItems.Count; loop++)
{
selected++;
}
if (selected > 1)
{
MessageBox.Show("only one meal allowed", "Halt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
How could I do a simlar thing with javascript?
kind regards
Arian
For instance, if you give your checkboxes a class you can do something like this:
var myboxes = document.getElementsByClassName('myboxes');
for (var i=0; i<myboxes.length;i++) {
if (myboxes[i].checked) {
alert('Box number '+i+' is checked!');
}
}
Simply put, give your form a unique id attribute. Then, traverse HTMLFormElement.elements and check against HTMLInputElement.checked for a truthy value.
HTML:
<form id="foo" method="post" action="./">
<input type="checkbox" name="check_a" value="foo" />
<input type="checkbox" name="check_b" value="bar" />
<input type="checkbox" name="check_c" value="baz" checked />
</form>
JS:
var foo = document.getElementById("foo"), i = 0, el;
for(i;i<foo.elements.length;i++)
{
el = foo.elements[i];
if(el.nodeType === 1 && el.tagName === "INPUT" && el.type === "checkbox")
{
//element node, is an input element, is a checkbox
if(el.checked)
{
//checkbox is checked
}
}
el = null;
}
Bonus reference:
HTMLFormElement (via DOM Level 2)
HTMLInputElement (via DOM Level 2)
Using a little bit of jQuery:
$(function() {
$('form').submit( function() {
if ($('[name="chkMeal"]:checked').length > 1) {
// show an error
return false; // cancel submit
}
});
});

Categories

Resources