How to check & uncheck checkbox onload function? - javascript

I have a code in which if my checkbox is checked and if I load window(page) checkbox should remain there on reload OR if I uncheck the checkbox and reload page then checkbox should remain unchecked. my code is as following.
<input type="checkbox" id="chk">
<script>
window.onload = onPageLoad();
function onPageLoad() {
if (document.getElementById("chk").checked == true) {
document.getElementById("chk").checked = true;
} else {
document.getElementById("chk").checked = false;
}
}
</script>
However above code returns unchecked checkbox even after reloading page after checking checkbox.

Just add "checked" attribute to HTML tag:
<input type="checkbox" checked>
But if you need to keep checked input after page reload you need to add a storage info. Maybe help:
<input type="checkbox" id="chk">
<script>
window.addEventListener('load', function() {
document.querySelector("#chk").addEventListener('change', function(el) {
console.log(el.target.checked);
localStorage.setItem('input_checked', el.target.checked );
});
if ( localStorage.getItem('input_checked') !== null ) {
document.querySelector('#chk').checked = localStorage.getItem('input_checked') === 'true';
}
});
</script>

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);
}
}

checkbox $.change is being triggered by itself and looping because it is being modified inside $.change

I have a group of checkboxes that when you click ONE, they should ALL be checked.
When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and $(".atpSelections").change is triggered only once per click.
Here's the code:
$(".atpSelections").change(function() {
console.log("CHANGED");
//Check ALL other checkboxes starting with that class name:
var className = $(this).attr("class");
className=className.replace("atpSelections ", "");
className=className.trim();
className=className.split("-");
//Get current checkbox state
var currentState = $(this).attr("checked");
//Now loop through all other checkboxes starting
//with the same class name and check them:
$("input[class*='"+className[0]+"-']").each(function(i){
//THIS IS TRIGGERING "$(".atpSelections").change"!!
if(currentState && currentState=="checked")
{
$(this).prop('checked', true);
}else
{
$(this).prop('checked', false);
}
});
});
The Problem
The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.
So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.
How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?
Attempts
I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.
Solution
I used #James 's answer and changed
var currentState = $(this).attr("checked");
to
var currentState = $(this).prop("checked") ? "checked" : "";
and it worked perfectly! Thanks.
Here's the JSFiddle: https://jsfiddle.net/zL7amo0y/
The problem is with your currentState variable. Please do a console.log on it. I'm guessing it's undefined?
Below is your code fixed in both jQuery and Vanialla JS.
JQuery:
$(".atpSelections").change(function() {
var currentState = $(this).prop("checked");
console.log(currentState);
$("input[name='checkboxToCheck']").each(function(i){
if(currentState)
{
$(this).prop('checked', true);
}else
{
$(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm">
<label for="checkbox1">Main Checkbox:</label>
<input class="atpSelections" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox2">Checkbox2:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox3">Checkbox3:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
</form>
Vanilla JS:
var checkbox = document.getElementById("checkbox1")
var checkboxToCheck = document.getElementsByName("checkboxToCheck");
checkboxToCheck = [].slice.call(checkboxToCheck);
function checkAllBoxes() {
checkboxToCheck.forEach((element) => {
if (checkbox.checked) {
element.checked = true;
} else {
element.checked = false;
}
});
}
checkbox.addEventListener("change", checkAllBoxes);
<form name="myForm">
<label for="checkbox1">Main Checkbox:</label>
<input value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox2">Checkbox2:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox3">Checkbox3:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
</form>
I'm thinking know what is your problem, I got it with a plugin of checkboxes too.
Try this
$(".atpSelections").on('change.custom', function(e) {
console.log("CHANGED CUSTOM");
//Check ALL other checkboxes starting with that class name:
var className = $(this).attr("class");
className=className.replace("atpSelections ", "");
className=className.trim();
className=className.split("-");
//Get current checkbox state
var currentState = $(this).attr("checked");
//Now loop through all other checkboxes starting
//with the same class name and check them:
$("input[class*='"+className[0]+"-']")
.off('change.custom')
.each(function(i){
//THIS IS TRIGGERING "$(".atpSelections").change"!!
if(currentState && currentState=="checked"){
$(this).prop('checked', true);
}else{
$(this).prop('checked', false);
}
});
});
Normally it's okay :)

auto-submit form only if specific number of checkboxes had been checked

I am new to jQuery. I am wondering if there is a way to count the number of checkboxes that have been checked and then auto-submit the form once a specific number of checkboxes had been checked. Let's say the user checks 2 checkboxes, nothing happens. The user checks the 3rd checkbox and the form submits.
<input type="checkbox" onclick="this.form.submit();">
You could try this, using no inline javascript...
HTML
<form>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</form>
jQuery
$('input[type="checkbox"]').on('click', function (event) {
var flag = $('input:checked').length > 2 ? true : false;
if (flag) $('form').submit();
});
Fiddle
$('input[type="checkbox"]').on('change', function() {
if( $("input[type="checkbox"]:checked").length >=3) {
$('form').submit();
}
});
JQuery function:
function SubmitIfReady() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
}
HTML (form not shown):
<input type="checkbox" class="checkbox-class" onclick="SubmitIfReady();">
Or without the onclick:
JQuery function:
$(document).ready(function () {
$('.checkbox-class:checked').on('change', function() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
});
});
HTML (form not shown):
<input type="checkbox" class="checkbox-class">
Like this...
$(".counted-check").click(function(e){
var myForm = $(this).closest('form');
if(myForm.find(".counted-check").filter(":checked").length > 3){
myForm.submit();
}
});
http://jsfiddle.net/HQ5N9/

Enable/Disable a button on select of radio button in jquery

I have a page in which there are 2 radio buttons and a next button. I have made next button disabled and it is enabled only when I select any radio button. But now when I go to another page and come back to this page the next button comes as disabled although the radio button is already selected. PFB the code
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
Try
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').click(function() {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
$('#commandButton_1_0').prop('disabled', !(checkval == '1' || checkval == '2'));
});
});
Demo: Fiddle
I took time to understand your problem,
This can be solved by unchecking the radio while loading the page.
$(document).ready(function () {
$('input:radio[name=a_SignatureOption]').prop('checked', false);
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
check out JSFiddle, btw redirect to other site and press back button to find the difference.
Hope you understand.
// Try this.............
$(document).ready(function () {
$("input:radio[name=a_SignatureOption]").removeAttr('checked');
$('#commandButton_1_0').attr("disabled","disabled");
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr("disabled","disabled");
}
});
});
It is simple as your question is
<form name="urfrm">
<input type="radio" value="1" name="a_SignatureOption"> Yes<br>
<input type="radio" value="2" name="a_SignatureOption"> No<br>
<input type="submit" id="butn" name="butn" value="next" disabled><br>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//This will check the status of radio button onload
$('input[name=a_SignatureOption]:checked').each(function() {
$("#butn").attr('disabled',false);
});
//This will check the status of radio button onclick
$('input[name=a_SignatureOption]').click(function() {
$("#butn").attr('disabled',false);
});
});
</script>
The easiest solution I can think of - albeit somewhat belatedly, is:
// selects all input elements, whose name is 'a_SignatureOption' and whose
// type is 'radio'
// binds a change event-handler, using 'on()':
$('input[name=a_SignatureOption][type="radio"]').on('change', function(){
// sets the 'disabled' property of the button to 'true' if zero radio inputs
// are checked, or to false if one is checked:
$('#commandButton_1_0').prop('disabled', $('input[name=a_SignatureOption][type="radio"]:checked').length === 0);
// triggers the change event-handler on page load:
}).change();
References:
Attribute-equals ([attribute="value"]) selector.
change().
on().
prop().
On load of document you need to check whether radio button is clicked or not
$(document).ready(function() {
$('input:radio[name=a_SignatureOption]').each(function() {
checked(this);
});
$('input:radio[name=a_SignatureOption]').click(function() {
checked(this);
});
function checked(obj){
if($(obj).is(':checked')) {
$('#commandButton_1_0').removeAttr('disabled');
}else{
$('#commandButton_1_0').attr('disabled', 'true');
}
}
});
You forgot to check the buttons at the beginning.
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
if( $('input[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
$('input[name=a_SignatureOption]').click(function () {
if( $('input:radio[name=a_SignatureOption]:checked' ).size() > 0 ) {
$('#commandButton_1_0').removeAttr('disabled');
}
});
});
By the way, I always suggest to add classes to form elements and work with those, instead of using [name="..."]. It's quicker and simplier and you can change input names (if necessary) without touching js
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#commandButton_1_0').attr('disabled', 'true');
$('input:radio[name=a_SignatureOption]').click(function () {
var checkval = $('input:radio[name=a_SignatureOption]:checked').val();
alert(checkval)
if (checkval == '1' || checkval == '2') {
$('#commandButton_1_0').removeAttr('disabled');
}
else {
$('#commandButton_1_0').attr('disabled', 'disabled');
}
});
});
</script>
</head>
<body>
<input type="radio" name="a_SignatureOption" value="1" /> value1
<br />
<input type="radio" name="a_SignatureOption" value="2"/> value2
<br />
<input type="radio" name="a_SignatureOption" value="3" checked="checked"/> value3
<br />
<input type="button" id="commandButton_1_0" value="Next"/>
</body>
</html>

Categories

Resources