Is this the proper way to use a checkbox? - javascript

Is this the proper way to use a checkbox in JS. I can only get the event to fire one time, not each time I click the box.
var checkbox = document.checkbox;
checkbox.addEventListener('change', function(){
switch(this.value){
case "on":
checkbox.value = "off"; break;
case "off":
checkbox.value = "on"; break;
}
<input type="checkbox" name = "checkbox" checked = "checked" value = "on">

You don't want spaces around your equals sign in HTML. Also, a switch statement is a little verbose for when you have less than three conditions.
Not sure what you are trying to accomplish exactly, but here you go.
var checkbox = document.querySelector('.checkbox');
checkbox.addEventListener('change', function(){
this.checked ? this.setAttribute('value', 'on') : this.setAttribute('value', 'off');
});
<input class="checkbox" type="checkbox" name="checkbox" />

Make sure to get a reference to the checkbox using the proper API:
// Get a reference to the element the proper way:
var checkbox = document.querySelector("input[type='checkbox']");
checkbox.addEventListener('change', function(){
switch(this.value){
case "on":
this.value = "off";
break;
case "off":
this.value = "on";
break;
}
console.log(this.value)
});
<input type="checkbox" name = "checkbox" checked = "checked" value = "on">
With that said, it's not super useful to change the value of a checkbox because it's checked. The usual way a checkbox is used is either to submit its value as part of a form submission or to use as a Boolean indicator of some state for "in-page" behavior. You generally don't want or need to change the value of a checkbox, instead you simply want to know if it is checked, which can be done by looking at its .checked property and making decisions based on that. A checkbox will have a checked property value of true when it's been checked and false when it isn't.
// Get a reference to the element the proper way:
var checkbox = document.querySelector("input[type='checkbox']");
checkbox.addEventListener('change', function(){
if(this.checked){
console.log("Checkbox is checked! Do something about it!");
} else {
console.log("Forget it. Checkbox wasn't checked.");
}
});
<input type="checkbox" name = "checkbox" value = "on">

No need of JS for this:
#chkBx + label { display:none; }
#chkBx:checked + label { display:inline; }
#chkBx:checked + label + label { display:none; }
<input type="checkbox" id="chkBx" checked ><label for="chkBx">On</label><label for="chkBx">Off</label>

Related

Update the status of checkboxes in html via js

I want a checkbox to be updated when a value changes. In this short example, if the second checkbox is checked, then the first should be update and checked, too. The functionality of the first checkbox should still stay intact. How can I achieve this?
function onoff() {
currentvalue = document.getElementById('onoff').value;
if (currentvalue == "Off") {
document.getElementById("onoff").value = "On";
console.debug("OFF");
} else {
document.getElementById("onoff").value = "Off";
console.debug("ON");
}
}
function xy() {
document.getElementById('onoff').value = "On";
console.debug("xy");
}
<input type="checkbox" value="On" id="onoff" onclick="onoff();">
<input type="checkbox" value="Off" id="xy" onclick="xy();">

checkbox onclick wont change checked via jscript

I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}

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

How use ClearText textarea When i am click radiobutton

1.Step(Unicode RadioButton is Checked) TextetArea notClear when Unidcode Radio is Checked But Zawgyi Radio is checked Textarea is Clear.
2.Step(Zawgyi RadioButton is Checked)TextetArea notClear when Zawgyi Radio is Checked But Unicode Radio is checked Textarea is Clear.
<label><input type="radio" name="kb" value="uni" id="unikb"/>Unicode</label>
<label><input type="radio" name="kb" value="zawgyi" id="zawgyikb"/>Zawgyi</label>
<textarea id="desp" class="form-control rows="5"></textarea>
How use Jquery
$("input").click(function(){
if ( $(this).val()=='uni' || $(this).val()=='zawgyi'){
$("textarea#desp").val();
}
else{
$("textarea#desp").val('');
}
}) ;
i wanted this style
textarea is not clear.
textarea is clear
AND
textarea is not clear.
textarea is clear
SEEDEMO
You had the else clausure wrong, jsfiddle fixed: http://jsfiddle.net/hLuk2bhx/9/
Now it's working... (:
$("input[type='radio']").click(function(e) {
if ( $(this).val()=='uni'){
$("textarea").val('');
}else{
$("textarea").val('');
}
});
After your comment i've updated your code making it more dynamic, i've create a var to control the last statement.
var lastChecked = undefined;
$("input[type='radio']").click(function(e) {
if ( $(this).val() != lastChecked && (typeof lastChecked !== 'undefined')){
$("textarea#desp").val('');
}
lastChecked = $(this).val();
});
Hope that it helps your problem.
Fiddle: http://jsfiddle.net/hLuk2bhx/23/
I have updated your code , plz see this JSFiddle
http://jsfiddle.net/hLuk2bhx/22/
Code changed
$("textarea#desp").val(); -> $("#desp").val(''); //You have to assign an "" empty string as its value to clear the textarea content
esle -> else
Added html as below
<input type="hidden" id="previouschecked" name="previouschecked" value="" / >
And I have added an input[hidden] to storethe previous value, So it should looks like
$("input[type='radio']").click(function(e) {
if ( $(this).val() !=$("#previouschecked").val()){
$("#desp").val('');
}
$("#previouschecked").val($(this).val());
});
Since you have an ID on your textarea so you can use $("#desp") directly
"esle" is a typo so your code is broken that won't run correctly

How to automatically uncheck checkbox if textbox is filled

I've made the checkbox to be default check. How can I uncheck the checkbox automatically if certain textfield is filled. I've thinking of using javascript.
I tried using this
<input type="text" name="commentID" id="commentID" onkeyup="userTyped('skipID', this)"/>
<input type="checkbox" name="skipID" value="N" id="skipID" checked="checked" />
and the javascript
function userTyped(commen, e){
if(e.value.length > 0){
document.getElementById(commen).checked=false;
}else{
document.getElementById(commen).checked=true;
}}​
It works but how if i have 3 textfield, and I want the checkbox to be filled only after all textfield is filled.
Just do this:
<input type="checkbox" id="someid" checked="checked"/>
<textarea onchange="if (this.value != '') document.getElementById('someid').checked = false;"></textarea>
if(document.getElementById('yourtextBox').value!=' ')
{
document.getElementById('checbox').checked=false;
}
Try the following code. In this code, each time when you type a character in the textfield, the function will be called and the length of the textfield value is not zero, the checbox will be unchecked and it will be checked while you clear your textfield
//Function get called when you type each letter
function OnChangeTextField(){
//getting the length of your textbox
var myLength = $("#myTextbox").val().length;
if(myLength > 0){
$("#myCheckbox").attr("checked", false);
}else{
$("#myCheckbox").attr("checked", true);
}
}
<input type = "text" id = "myTextbox" onkeyup= "OnChangeTextField();"/>
<input type="checkbox" id = "myCheckbox" value = "true" checked = "checked"/>
$("#comment").on("keyup blur", function () {
$("#box").prop("checked", this.value == "");
});
EDIT: You can also use jQuery
$("#comment").on("keyup blur", function() {
$("#box").prop("checked", this.value == "");
});
Try jQuery, This works for me...

Categories

Resources