HTML Checkboxes with Javascript Functions - javascript

I'm just trying to get this checkbox to alert a message after it is checked and after it is unchecked by running a function in Javascript. I can get it to display the "checked" message but can't get the "unchecked" alert to come up.
<input type="checkbox" id="chbx" onchange="foo()">
<script type="text/javascript">
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
alert("Checked!");
}
else {
alert("UnChecked!");
}
};
</script>

You've got single-equals instead of double-equals in your if statements:
if (checkbox.checked=true) {
should be
if (checkbox.checked == true) {
or just
if (checkbox.checked) {

You are not comparing values using =. Needs to be at least ==, better ===
if(checkbox.checked === true) {}
or, simplified
if(checkbox.checked) {}

You made the commonly made mistake of using a single = this actual sets the checkbox.checked to true. If you want to make a comparison make sure to use a double ==.
Also, there are only two options for a checkbox; so if it's not on it's off:
This is what I would have done:
<input type="checkbox" id="chbx" onchange="checkbox_changed()">
<script type="text/javascript">
var checkbox = document.getElementById("chbx");
function checkbox_changed() {
if (checkbox.checked == true) {
alert("Checked!");
} else {
alert("UnChecked!");
}
}
</script>

Related

JQuery - Checkbox not returning correct value for "checked"

For the checkbox, i've put a function that will add on the checked property dynamically as below
if ($(_this).prop("checked") == true) {
$(_this).attr('checked', 'checked');
}
else if ($(_this).prop("checked") == false) {
$(_this).removeAttr('checked');
}
when it shows the below as the property for the checkbox
<center><input onclick=\"CheckboxIsChecked(this)\" type=\"checkbox\" checked=\"checked\"></center>
but when a function catch whether there is the checked property in the element as below. it would always return a false. What is wrong with my code?
$(List[i].Checkbox).prop("checked") ? true : false
You can use is(":checked") to determine whether checkbox is checked or not:
function CheckboxIsChecked(elem) {
console.log($(elem).is(":checked"));
return $(elem).is(":checked");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center><input onclick="CheckboxIsChecked(this)" type="checkbox"></center>

How to check if checkbox is checked in asp.net view using Jquery?

I am trying to find out whenever a checkbox on my page is checked and unchecked. I console log to find out the status, but I am always getting an "unchecked" result. What am I doing wrong?
...
<input type="checkbox" id="checkbox_addAuthor" name="checkbox_addAuthor" />
</div>
</form>
#section Scripts
{
<script type="text/javascript">
var checkbox = $('#checkbox_addAuthor');
var authorList = $('#AuthorList');
checkbox.on('click',function(){
if(checkbox.Checked == true)
{
console.log("I am checked")
}
else {
console.log("I am not checked");
}
})
</script>
}
When I run this, the console always prints out "I am not checked". Cant figure out why.
you can use the prop
if($('#checkbox_addAuthor').prop('checked'))
{
// something when checked
}
else {
// something else when not
}
$('#checkbox_addAuthor :checkbox:checked').length > 0;
Use $('#checkbox_addAuthor').val() == "on" to check the state of the checkbox

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!!

JS - if hidden field's value is "x," then execute function

I think this is pretty simple, but I am writing 1 JavaScript include that will go on multiple pages with a form. All of the pages have a hidden field like this:
<input type="hidden" name="test" value="test1">
Some pages have the value as "test1," while others have "test2." I only want to execute this script for pages with the "test1" value. I do NOT want it on pages with "test2" value.
For reference, here is the JS:
function CheckDay(obj) {
if (obj.value == "F") {
document.getElementsByName("price")[0].value = "29.99";
} else {
document.getElementsByName("price")[0].value = "39.99";
}
}
I'm just not sure how to say, only run if "test" value is "test1". Can anyone help?
You can add condition in the funnction to execute the javascript only when the value of test is test1 (Or you can call the function CheckDay from another function after checking the value)
function CheckDay(obj) {
if(document.getElementsByName('test')[0].value==='test1'){
if (obj.value == "F") {
document.getElementsByName("price")[0].value = "29.99";
} else {
document.getElementsByName("price")[0].value = "39.99";
}
}
}

Why does the order of Boolean values affect this program?

I created a basic program where user input is turned into an alert on submission. I can't figure out why the program only works as intended if I use false rather than true as the first condition in my if/else statement. I'm sure this is very basic but I've failed to find anything of relevance. After a long search I decided to post the question. Any answers will be greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.
Because your input is a string. And string == true will be false.
You can set breakpoints to check them.

Categories

Resources