Ckeckbox check works when clicked on label only - javascript

I have a situation where I need to change the value of the checkbox whether it's checked or not for error validation purposes.
The setup is like this
jQuery(document).ready(function($) {
"use strict";
function toggle_checkbox_value(e) {
var $this = $(e.currentTarget);
e.preventDefault();
if (!$this.data('lockedAt') || +new Date() - $this.data('lockedAt') > 300) {
var $input_terms = $('#terms');
if ($input_terms.val() == '0') {
$input_terms.val('1');
$input_terms[0].checked = true;
} else {
$input_terms.val('0');
$input_terms[0].checked = false;
}
}
$this.data('lockedAt', +new Date());
}
$(document).on('click', 'label[for="terms"]', toggle_checkbox_value)
.on('click', '#terms', toggle_checkbox_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" name="terms" value="0">
<label for="terms" class="checkbox">I've read and accept the terms & conditions</label>
I've tried with .attr('checked', 'checked') and with .prop('checked', true) but nothing I did seems to work.
When I click on label, the checkbox will be checked (check mark shown), but when I click on the checkbox, the value changes in DOM when I inspect it, but the check mark is not shown.
What seems to be the issue here?

I am not sure what you are trying to do. But this will work
However your server will only retrieve the terms' value if the checkbox is checked so just test if it is set on the server
jQuery(document).ready(function($) {
"use strict";
$("#terms").on('click',function() {
this.value=this.checked?1:0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" name="terms" value="0">
<label for="terms" class="checkbox">I've read and accept the terms & conditions</label>

Related

Disabling a checkbox if a condition is met

I'm pretty new to Javascript and I have an exercise containing a form and some validation checks,
I have a few inputs such as name, price, and a checkbox and I'm trying to disable the checkbox based on the price input (disable it if it's above 200 and re-enable it if it's less than 200), and at the moment it's not working,
I'll really appreciate suggestions.
That's the Javascript code I've written:
document.addEventListener("DOMContentLoaded", function () {
const price = document.querySelector("[name='purchasePrice']");
price.addEventListener("change", checkPrice);
function checkPrice() {
if (price > 200) {
document.querySelector("[name='chkBx']").disabled = true;
} else {
document.querySelector("[name='chkBx']").disabled = false;
}
}
});
and this is the HTML code:
<div class="item-div">
<label>
Purchase Price
<input
class="inputClass"
type="number"
name="purchasePrice"
min="1"
required
/>
</label>
</div>
<div class="item-div">
<label>
Add Charge
<input type="checkbox" name="chkBx" />
</label>
</div>
Just put a parameter name e in checkprice function.And then you will get access to the target value in change event then your function will work fine.
func checkprice (e)
if(e.target.value > 250)
disable true
else
disable false
end of function
Hope it helps.

Check checkbox based on variable value

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren
I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

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/

Difficulty inserting variable into jquery attribute identification

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});

Categories

Resources