Checking the checkbox in jquery - javascript

I am beginner webdeveloper;
I make my project in Html/Css/jQuery.
I have 5 checkboxes on the website. 3 of them have the checkboxRequired class. After clicking on each of the 5 checkboxes, I have to check if all 3 checkboxes with the checkboxRequired checkout are selected.
I try this solution:
$('input[type="checkbox"]').click(function(){
if($('input:checkbox.checkboxRequired').prop('checked')){
console.log("Checkbox is checked.");
}
else {
console.log("Checkbox is unchecked.");
}
});
but it's always show: Checkbox is unchecked.
How can I repair it?
Please help me.

You need to use the .is() method and the :checked selector.
On clicking of a checkbox - you iterate over the checkboxes with the required class (using the .each() method) and can test each to see if its checked or not.
Note the little ternary equation in there to demonstrate an alternative to the traditional if/ else block - but it does the same thing (the "?" line is equivalent to true and the ":" is equivalent to false / else....
EDIT - I have updated the function to match your needs. Basically you need to check if all the checkboxes are checked and if so - submit the form and if not - raise the error modal.
The following amended code should do that for you.
$('input[type="checkbox"]').click(function(){
let total = 0;
let checked = 0;
$('.checkboxRequired').each(function(index){
total += 1;
if( $(this).is(':checked') ) {checked +=1 }
})
total === checked
? ($('.orderForm').submit(), console.log('Form Submitted'))
: $('#errorModal').modal('show');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 1</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 2</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 3</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 4</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 5</label>
<!-- form
<form class="orderForm" method="post"></form>
-->
<!-- Modal -->
<div id="errorModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Error Modal Header</h4>
</div>
<div class="modal-body">
<p>There is a disturbance in the force..... not all required checkboxes are checked</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

You can check the checked status in the element itself. Like this:
$('input[type="checkbox"]').click(function(){
if($('input:checkbox.checkboxRequired')[0].checked){
console.log("Checkbox is checked.");
}
else {
console.log("Checkbox is unchecked.");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxRequired">

I would try to check if all 3 checkboxes with the .checkboxRequired are selected in this way:
$('input[type="checkbox"]').click(function(){
const checkboxes = $('.checkboxRequired:checked');
if (checkboxes.length === 3) {
console.log("All 3 required checkboxes are checked.");
} else {
console.log("Some required checkbox is unchecked.");
}
});
Demo - https://codepen.io/vyspiansky/pen/NWNrLXN

Because $('input:checkbox.checkboxRequired') is select all elements by that selector. But prop method works with first element only:
Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.
Link to docs:
https://api.jquery.com/prop/
Depending on your needs, you can handle it in other ways:
Simplest way: you can use attribute required - see docs
If you need more custom way, you can do something like that:
var $form2 = $('form#action2')
$form2.submit(function(e){
var isAllReqChecked = true
$form2.find('input:checkbox.checkboxRequired')
.each(function propChecker(){
isAllReqChecked &= $(this).prop('checked')
})
alert(isAllReqChecked ? 'All required was checked!' : 'Not all required was checked')
e.preventDefault()
});
Check demo

Related

How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked

I've been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit.
This is my JS:
function checkBoxes() {
$(' input[type=checkbox]').
attr('disabled', true);
$(document).on('click',
'input[type=checkbox]',
function (event) {
if ($(this).is(":checked")) {
console.log("1")
} else {
console.log('2')
}
});
}
The issue I'm having trying to figure this out is how to verify if the box has been checked or not because of how I'm creating the checkbox list with Django:
<div style="height:30px"></div>
<form method="post">
{% csrf_token %}
{{ context.form.as_p }}
<button type="submit">Submit</button>
</form>
How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again?
Just use
:checked and :not(:checked) in your jquery selector, like this:
$(document).on('click', 'input[type=checkbox]', function(event) {
if ($('.checkbox-container input[type=checkbox]:checked').length >= 3) {
$('.checkbox-container input[type=checkbox]:not(:checked)').attr('disabled', true);
} else($('.checkbox-container input[type=checkbox]').attr('disabled', false));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<div class="checkbox-container">
<input type="checkbox" id="scales1" name="scales1" checked>
<input type="checkbox" id="scales2" name="scales2" checked>
<input type="checkbox" id="scales3" name="scales3">
<input type="checkbox" id="horns1" name="horns1">
<input type="checkbox" id="horns2" name="horns2">
<input type="checkbox" id="horns3" name="horns3">
</div>
</body>
</html>

How to capture whether a checkbox has been checked or not?

I have a Bootstrap form modal being used for a webinar signup. I've removed the other fields, but I have multiple text fields that are being captured and pushed to a CMS.
It's just these 3 checkboxes that I can't seem to get to push data across correctly. The checkboxes are recording all as "on" if the form is submitted once, but if the form is submitted a second time then the checkboxes that are checked/not checked will push through "on" and "off" accordingly. So it works on the second submit, but not on the first. Any help would be greatly appreciated. I'm new to javascript and jquery, so i'm now at the point of guessing.
$(document).ready(function() {
$('.register-webinar').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must select at least one session.");
return false;
}
});
$('input.webinar').change(function() {
if ($(this).is(":checked")) {
$(this).val("on")
} else {
$(this).val("off")
}
});
$('#railway_form').on("submit", function(e) {
e.preventDefault();
setTimeout(AoProcessForm(this), 200);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<div class="form-popup-bg">
<div class="form-container">
<button id="btnCloseForm" class="close-button">X</button>
<h1 style="text-align:center;">Register your attendance</h1>
<p style="text-align:center;">Please select which session/s you wish to attend.</p>
<form name="railway_webinar" id="railway_form" class="railway_webinar" action="">
<div class="form-group">
<input type="checkbox" id="Webinar_1" name="Webinar_1" class="webinar">
<label for="Webinar_1">webinar 1</label><br/>
<input type="checkbox" id="Webinar_2" name="Webinar_2" class="webinar">
<label for="Webinar_2">webinar 2</label><br/>
<input type="checkbox" id="Webinar_3" name="Webinar_3" class="webinar">
<label for="Webinar_3">webinar 3</label>
</div>
<input type="submit" value="Reserve my seat!" class="form-block-cta register-webinar" />
</form>
</div>
</div>
Figured it out. All I needed to do was set the checkbox value to "off", as they would all be "on" by default.

Bootstrap set radio button checked with jquery

I have radio buttons in my html code.
I want to change their state based on my input values via jquery
Here is My Html
<div class="col-md-2 col-xs-offset-1">
<div class="radio">
<label>
<input type="radio" name="rdo_pkdrop" value="0" id="rdo_pick">
Pick-up Time
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="rdo_pkdrop" id="rdo_drop" value="1">
Drop Time
</label>
</div>
</div>
An jQuery is
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{
$('#rdo_pick').prop('checked',true);
}
But This has no effect
I also tried with
$('#rdo_pick').prop('checked','checked'); and
$('#rdo_pick').attr('checked','true');
$('#rdo_pick').addClass('checked');
This is only way I could find. Although somewhat inelegant, it does work.
if(qs_trip_type == 0){
$('#rdo_pick').click();
}else{
$('#rdo_drop').click();
}
The issue with bootstrap is that you set a checked radio button by adding the active class to the corresponding label of the input. It looks like this:
<label class="btn btn-default active"> <!-- Note the class 'active' here -->
<input type="radio" name="myRadio" value="value1" checked="checked"/>Value 1
</label>
<!-- ... -->
To check a radio button using jQuery you could first select the input field with a jQuery Selector and then add the class to the parent:
var $myRadioInput = $(...);
$myRadioInput.parent('.btn').addClass('active');
Don't forget to remove the class active on the formerly selected label with jQuery removeClass('active') to first unselect them.
I also like it to set the checked property on the input itself to have the proper state on it:
$myRadioInput.prop('checked', true);
Note that the checked="checked" attribute is only the inital state for the input to be the checked input when loading the page. It does NOT change with the jQuery .prop() method, as it is an attribute and is different to the actual checked property. This is well described in jQuery Docs.
I have tried,this code is ok for bootstrap radio.
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true).click();
}else{ //not ekse
$('#rdo_pick').prop('checked',true).click();
}
there is a typo in your code replace ekse with else
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{
$('#rdo_pick').prop('checked',true);
}
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{ //not ekse
$('#rdo_pick').prop('checked',true);
}
Here's the jsfidlle http://jsfiddle.net/urLh9qnh/
Try this
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{
$('#rdo_drop').prop('checked',true);
}
Try This:
after setting the value of the radio, please add this code
$("input[type='checkbox'], input[type='radio']").iCheck({
checkboxClass: 'icheckbox_minimal',
radioClass: 'iradio_minimal'
});
Here is a one line solution:
$('#rdo_pick').iCheck('check');

Need to get Result from filtering item

I have simple code for filtering multiple item, so far its working
Here is the code :
<div class="container btn-group tags" data-toggle="buttons">
<label class="btn btn-primary active" id="myBtn">
<input type="checkbox" rel="arts" /> Arts
</label>
<label class="btn btn-primary" id="myBtn">
<input type="checkbox" rel="computers" /> Computers
</label>
<label class="btn btn-primary" id="myBtn">
<input type="checkbox" rel="health" /> Health
</label>
<label class="btn btn-primary" id="myBtn">
<input type="checkbox" rel="video-games" /> Video Games
</label>
</div>
<div class="container">
<div class="results">
<div class="container arts computers">
Result 1
</div>
<div class="container video-games">
Result 2
</div>
<div class="container computers health video-games">
Result 3
</div>
<div class="container arts video-games">
Result 4
</div>
</div>
</div>
and this is the script :
$('div.tags').delegate('input[type=checkbox]', 'change', function()
{
var $lis = $('.results > div'),
$checked = $('input:checked');
if ($checked.length)
{
var selector = $checked.map(function ()
{
return '.' + $(this).attr('rel');
}).get().join('');
$lis.hide().filter(selector).show();
}
else
{
$lis.show();
}
});
My question is, if i have filter let said A - Z letter, and some one select A & M how to displaying the letter that he selected? and give an option to clear all the field by clicking clear button?
here is the fidle http://jsfiddle.net/nucleo1985/g9SAQ/
Thanks,
Updated your fiddle to ALERT when a box is checked (so you can see how to display value of checkbox checked) and added a button to clear all (so you can see how to reset result list and clear all checkbox checks)
Working Fiddle Demo
<button onclick="$('input:checkbox').removeAttr('checked');$('.results > div').show();$('.checkedItem').html('');">Clear All</button>
i've added a new div to put the last checked box value into:
<div class="checkedItem">checked item will go here once clicked</div>
and here is how its put in:
$('.checkedItem').html($(this).attr('rel'));
Remove the id="myBtn" as id must be unique and add class category to the checkboxes
Also add a checkbox whose id is clear to clear the div like,
$('div.tags').delegate('#clear', 'change', function() {
$('.category').prop('checked',false);
$('.results > div').hide();
});
And modfy your category checkboxes like,
$('div.tags').delegate('input[type=checkbox].category', 'change', function() {
if($('.category:checked').length){// if clear is checked then uncheck it
$('#clear').prop('checked',false);
}
var $lis = $('.results > div'),
$checked = $('input.category:checked');
if ($checked.length){
var selector = $checked.map(function (){
return '.' + $(this).attr('rel');
}).get().join(', '); // join the array with ', '
$lis.hide().filter(selector).show();
} else{
$lis.show();
}
});
Demo
Updated, if you want to show active div's try this,
CSS
.active{
background:#BBE4E7;
}
In Jquery replace the lines
$lis.hide().filter(selector).show(); by $lis.removeClass('active').filter(selector).addClass('active');
$('.results > div').hide(); by $('.results > div').removeClass('active');
Updated Demo

Check to see if none of the checkboxes was checked in jquery

I have two checkboxes and one of the checkboxes must be checked. I can see that it's right, no syntax errors. What should be made to my code to check if none of the checkboxes were checked?
HTML :
<input type="checkbox" value="aa" class="first" name="a"> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b"> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
JavaScript:
$('button').on('click',function(){
if( $(".first:not(:checked)") && $(".second:not(:checked)") ){
$('.error').text('You must select atleast one!');
}else
$('.error').hide();
});
Example : http://jsfiddle.net/ptbTq/
Check this fiddle: http://jsfiddle.net/692Dx/
Checking code:
if($('input[type="checkbox"]:checked').length == 0) {
alert('none checked');
}
You are using selectors which do not return boolean values which is what you need when writing an if condition. Here's what you could do:
$('button').on('click',function() {
if(!$(".first").is(":checked") && !$(".second").is(":checked")) {
$('.error').text('You must select atleast one!').show();
} else {
$('.error').hide();
}
});
or if you prefer and think it could be more readable you could invert the condiciton:
$('button').on('click',function() {
if($(".first").is(":checked") || $(".second").is(":checked")) {
$('.error').hide();
} else {
$('.error').text('You must select atleast one!').show();
}
});
Also notice that you need to .show() the error message in the first case as you are hiding it in the second.
And here's a live demo.
Short:
$("input[type=checkbox]").is(":checked")
returns true if:
one of your checkboxes - from the selector ("input[type=checkbox]") - is checked.
else return false
and in your case:
$(".first, .second").is(":checked")
Do something at least one of your checkboxes is checked
Put the same class on both checkboxes and you can do something like
if ($(':checkbox.the_class:checked').length > 0) {
// at least one checkbox is checked
// ...
}
The best would be to put your checkboxes inside a div with an unique ID so you can verify all the checkboxes in there, so your code will work in all cases. Even when adding new checkboxes to the div later on.
<div id="cb">
<input type="checkbox" value="aa" class="first" name="a" /> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b" /> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
</div>
Your JQuery:
$('button').click(function() {
var checked_one = $('div#cb input[type="checkbox"]').is(':checked');
if (!checked_one )
$('.error').text('You must select atleast one!');
else
$('.error').hide();
});
Live demo can be seen here: http://jsfiddle.net/ptbTq/15/

Categories

Resources