javascript get the value of checkbox if checked without button clicked - javascript

javascript get the value of checkbox if checked without button clicked
I am struck in the middle of project, please help..
how to get the check box value from the class name or from by name or by id through alert so that the particular value I can pass...
I am sorry to ask..I am new the jquery and javascript..
This is my HTML ...
<input type="checkbox" name='cbox' value="red" class="theClass"/>red
<input type="checkbox" name='cbox' value="green" class="theClass"/>green
<input type="checkbox" name='cbox' value="yer" class="theClass"/>yer
<input type="checkbox" name='cbox' value="asdasd" class="theClass"/>asdasd
<input type="checkbox" name='cbox' value="radgdfged" class="theClass"/>radgdfged
$(function(){
$('input[type=checkbox]').on('change', function() {
alert($(this).val());
console.log($(this).val());
});
});
I googled much ...but every where onclick the button than only will get all checkbox values..
I am getting the values using the onclick button ....but the thing is getting the value without using the button...
My concern is getting the value if checkbox is checked..
eg: if i checked red , i should get alert 'red'.....

jQuery:
$('input[type=checkbox]').on('change', function() {
console.log($(this).val());
});
Javascript:
var cbs = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i < cbs.length; i++) {
cbs[i].addEventListener('change', function() {
console.log(this.value);
});
}
EDIT:
If you want the value only if the checkbox is checked.
jQuery:
$('input[type=checkbox]').on('change', function() {
if($(this).is(':checked'))
console.log($(this).val());
});
Javascript:
var cbs = document.querySelectorAll('input[type=checkbox]');
for(var i = 0; i < cbs.length; i++) {
cbs[i].addEventListener('change', function() {
if(this.checked)
console.log(this.value);
});
}
jsfiddle DEMO
P.s. for jQyery put your code inside:
$(function() {
//code here
});

If you need to get all the checked checkboxes on change of checkboes, you can use:
$('.theClass').change(function(){
alert($('.theClass:checked').map(function(){return this.value}).get())
});
Working Demo

try:
<input type="checkbox" name='cbox' value="red" class="theClass" onchange="alert(this.value)"/>red
demo
EDIT:
<input type="checkbox" name='cbox' value="red" class="theClass" onchange="this.checked?alert(this.value):null"/>red
demo
EDIT
alert all checked input values:
$('input[type=checkbox]').on('change', function() {
if($(this).is(':checked')){
var values = [];
$.each($('input:checked'),function(index,input){
values.push(input.value);
});
alert(values.join(','));
}
});
demo

HTML
<input type="checkbox" name='cbox' value="red" class="theClass" checked/>
jQuery
$(function() {
$(":checkbox").each(function() {
alert($(this).val())
});
});

Javascript get the value of checkbox if checked without button clicked
This code is working fine.Try this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Values of Selected Checboxes</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input[type=checkbox]").change( function() {
var values = [];
$.each($('input:checked'),function(index,input){
values.push(input.value);
});
alert(values.join(','));
var n = $( "input:checked" ).length;
alert(n);
});
});
</script>
</head>
<body>
<form id="booking_form">
<input type="checkbox" name="bType" id="bType" value="A,200"> Type A - USD200<br>
<input type="checkbox" name="bType" id="bType" value="B,150"> Type B - USD150<br>
<input type="checkbox" name="bType" id="bType" value="C,100"> Type C - USD100<br>
<input type="checkbox" name="bType" id="bType" value="D,50"> Type D - USD50<br>
</form>
</body>
</html>
Preeti Dua

Related

Checkbox check first time not working, after second time, it is OK

I am trying to create a checkbox with label. When user click the label, it will check if checkbox checked. The first time, I click the label, the box is checked, but no alert action. After I click the second time, it start to function, alert action happen. What did I do wrong. I have tried to use individual ID. Click not working either.
<script type="text/javascript">
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+ id_name).click(function(){
if ($('#'+id_name +'_checkbox').prop('checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
</script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
<script type="text/javascript">
$('label').click(function() {
if ($('#'+ $(this).attr('id') + '_checkbox').prop('checked') === false) {
alert('Checked');
}
else {
alert('Unchecked');
}
});
</script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
Also be sure, you have included jQuery library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
And in new version of jQuery you can use insted of this:
if ($('#'+ $(this).attr('id') + '_checkbox').prop('checked') === false) {
alert('Checked');
}
else {
alert('Unchecked');
}
This piece of code:
// Just be careful, its inverted. Because, when you click label to check checkbox, the checkbox is still unchecked, and after alert will be checked...
if ($('#'+ $(this).attr('id') + '_checkbox').is(':checked') {
alert('Unchecked');
}
else {
alert('Checked');
}
Workind DEMO here in jsFiddle
Simplify things, you don't need each loop:
$('label').click(function() {
name=this.id;
if ($('#'+name+'_checkbox').prop('checked')) {
alert('Checked');
}
else{
alert('unchecked');
}
});
Demo: http://jsfiddle.net/fqvajvo1/2/
Script running correctly, script checks prop, but on label click -> checkbox is really unchecked, property changing comes later.
So, maybe in your case reverse logic could help (if you need alerts at all):
http://jsfiddle.net/fqvajvo1/4/ :)
I always use .is(':checked').I find it way more reliable
<script type="text/javascript">
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+id_name +'_checkbox').change(function(){
if ($(this).is(':checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
</script>
your click id is not complete name,so add complete name and call $(this) property will be ok...
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+ id_name+'_checkbox').click(function(){
if ($(this).prop('checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
Use .on to work for all events and all clicks on jQuery
Mainly used for dynamic creating elements
$(document).on('click','selector',function(){
});
Use class names for best options for grouped elements

jQuery / JavaScript: Check all checkboxes and Check each checkbox to display div

I am having a hard time figuring this out. I tried to make a global checkbox that will check all other sub-checkboxes and display a div, which works fine, but the issue is when i try to make each sub-checkboxes check and display the div themselves.
I wrote jquery hide and show for it.
When I check the first sub-checkbox, and check the second; the div displays but when i go back and uncheck the first one, the div closes and one and on due to the hide and show function, how can i do this?
Here is my code below.
<script>
$(document).ready(function(){
$('#checkbox-global').click(function(){
if($(this).is(':checked'))
$('.checkbox-group').prop('checked', true);
else
$('.checkbox-group').prop('checked', false);
});
});
$(document).ready(function(){
$('#checkbox-global').click(function(){
if($(this).is(':checked'))
$('.loaded').show(1000);
else
$('.loaded').hide(1000);
});
});
$(document).ready(function(){
$('.checkbox-group').click(function(){
if($(this).is(':checked'))
$('.loaded').show(1000);
else
$('.loaded').hide(1000);
});
});
<!-- The Div -->
<div class="loaded">RESTORE | DELETE</div>
<!-- The Global Checkbox -->
<input type="checkbox" id="checkbox-global" class="checkbox-group">
<br>
<!-- The Sub-checkboxes -->
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
You don't need to use document.ready multiple times, one is enough. This is to ensure that all DOM structure is ready and you can get the desired element at that point.
following are the points to consider
1) No need to bind click event twice for checkedLength, you can put checkbox check/uncheck and div show / hide logic in same click event handler.
2) You can check if any other checkbox is checked from checkbox-group, if none is checked then hide div otherwise show it.
$(document).ready(function(){
$('#checkbox-global').click(function(){
// check uncheck checkbox as per checked status
$('.checkbox-group').prop('checked', $(this).is(':checked'));
//show hide div
if($(this).is(':checked'))
$('.loaded').show(1000);
else
$('.loaded').hide(1000);
});
$('.checkbox-group').change(function(){
//check if checkbox-group have atleast one checkbox checked
var checkedLength = $('.checkbox-group:checked').length;
if(checkedLength > 0)
$('.loaded').show(1000);
else
$('.loaded').hide(1000);
});
});
You have to check for any of the check boxes is checked and if yes don't hide the div
Here is a sample code:
$(document).ready(function(){
$('#checkbox-global').click(function(){
if($(this).is(':checked')){
$('.checkbox-group').prop('checked', true);
$('.loaded').show(1000);
}
else {
$('.checkbox-group').prop('checked', false);
$('.loaded').hide(1000);
}
});
$('.checkbox-group').click(function(){
var cnt = $(".checkbox-group:checked").length;
if(cnt > 0)
$('.loaded').show(1000);
else
$('.loaded').hide(1000);
});
});
Try this code:
HTML
<!-- The Div -->
<div class="loaded">RESTORE | DELETE</div>
<!-- The Global Checkbox -->
<input type="checkbox" id="checkbox-global" class="checkbox-group">
<br>
<!-- The Sub-checkboxes -->
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
<input type="checkbox" class="checkbox-group">
jQuery
$(function () {
$(".loaded").hide();
$("#checkbox-global").click(function () {
if ($("#checkbox-global").is(":checked")) {
$(".checkbox-group").prop("checked", true);
} else {
$(".checkbox-group").prop("checked", false);
}
});
$(":checkbox").click(function () {
if ($(".checkbox-group").is(":checked")) {
$(".loaded").show(1000);
} else {
$(".loaded").hide(1000);
}
});
});
Try this
$(document).ready(function(){
var c = $('.checkbox-group').size(); //This line is used to count checkbox
$('#noc').html(c);
$('#checkbox-global').click(function(){
if($(this).is(':checked')) {
var nocf = $(":checked").size()
$('#noch').html(nocf);
$('.checkbox-group').prop('checked', true);
$('.loaded').show();
}
else {
$('.checkbox-group').prop('checked', false);
$('.loaded').hide();
var nocf = $(":checked").size()
$('#noch').html(nocf);
}
});
$('.checkbox-group').click(function(){
var tom = $('#checkbox-global').is(':checked');
if(tom == true || $('.checkbox-group').is(':checked')) {
var nocf = $(":checked").size()
$('#noch').html(nocf);
console.log($(":checked").size()); //This line is used to count checked checkbox
$('.loaded').show();
}
else{
$('.loaded').hide();
var nocf = $(":checked").size()
$('#noch').html(nocf);
}
});
});
$(function() {
var checked = true;
$("#all_check").on("change", function() {
checked = $(this).is(':checked');
if (checked) {
$('.dg-img').prop('checked', true);
}
else
{
$('.dg-img').prop('checked', false);
}
});

Select/Deselect All dynamic checkboxes in Rails 4 with Javascript

I have followed this StackOverflow Question's Answer1 and Answer2
but not getting result.. As I am calling all checkbox list's data from Range tabel. and their id is also defined by data.. Let me show you the code for this screenshot
= f.collection_check_boxes :range_ids, Range.active, :id, :name, {},:class=>'checkbox'
which returns as
<input id="campaign_range_ids_1" class="checkbox" type="checkbox" value="1" name="campaign[range_ids][]">
<input id="campaign_range_ids_2" class="checkbox" type="checkbox" value="2" name="campaign[range_ids][]">
<input id="campaign_range_ids_3" class="checkbox" type="checkbox" value="3" name="campaign[range_ids][]">
<input id="campaign_range_ids_4" class="checkbox" type="checkbox" value="4" name="campaign[range_ids][]">
I want if All means id="campaign_range_ids_4" is selected/deselected then all other check-boxes should be perform accordingly..
Here also have a screenshot of Range Table
I had tried this Javascript
:javascript
$('#campaign_range_ids_4').click(function() {
if(this.checked) {
$('#campaign_range_ids_1').checked = true;
$('#campaign_range_ids_2').checked = true;
$('#campaign_range_ids_3').checked = true;
});
} else {
$('#campaign_range_ids_1').checked = false;
$('#campaign_range_ids_2').checked = false;
$('#campaign_range_ids_3').checked = false;
});
}
});
Please correct me where I do Mistake.... Thanks in advance.. :)
Updated Question
I have followed Shridhar's and Pavan's answer it works perfectly but now I want that when I select All then deselect any one then it must uncheck "All" (4th checkbox) but it remains as it is..
As i said,it should be $('#campaign_range_ids_4') not $('#campaign_beacon_range_ids_4')
This will work too
$('#campaign_range_ids_4').click(function() {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
Demo
Error in Selectors ,It should be $('#campaign_range_ids_4') not $('#campaign_beacon_range_ids_4') use prop() to set the checkbox state
Try this
$('#campaign_range_ids_4').click(function () {
if ($(this).is(':checked')) {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', true);
} else {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', false);
}
});
DEMO
OR
$('#campaign_range_ids_4').click(function () {
$('#campaign_range_ids_1, #campaign_range_ids_2, #campaign_range_ids_3').prop('checked', $(this).is(':checked'));
});
DEMO
change the selector to $('#campaign_range_ids_4')and do this:
$('#campaign_range_ids_4').change(function() {
$('#campaign_range_ids_1, #campaign_range_ids_2, #campaign_range_ids_3').prop('checked', this.checked);
});
instead of click use change method.
Modifying Sridhar's answer finally I got the Answer of my Updated Question's.
I wanted if All(4th checkbox) is checked then all check-box should be selected and if it's unchecked then all check-box should be unchecked it works perfectly
But Issue I had found that If All(4th checkbox) is selected then it check all boxes then if I unchecked any check-box then All(4th checkbox) must be uncheked which was not occur.
Solution by Modifying Code: In future if other people face the same issue..
HTML Code:
<input id="campaign_range_ids_1" class="checkbox" type="checkbox" value="1" name="campaign[range_ids][]">London
<input id="campaign_range_ids_2" class="checkbox" type="checkbox" value="2" name="campaign[range_ids][]">India
<input id="campaign_range_ids_3" class="checkbox" type="checkbox" value="3" name="campaign[range_ids][]">USA
<input id="campaign_range_ids_4" class="checkbox" type="checkbox" value="4" name="campaign[range_ids][]">All
JavaScript:
$('#campaign_range_ids_4').click(function () {
if ($(this).is(':checked')) {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', true);
} else {
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').prop('checked', false);
}
});
$('#campaign_range_ids_1,#campaign_range_ids_2,#campaign_range_ids_3').click(function () {
if ($(this).is(':checked')) {
} else {
$('#campaign_range_ids_4').prop('checked', false);
}
});
Working Demo:

validating at least one checkbox selected on dynamically added fields

If you're dynamically adding form fields to an existing form, what's the best way of adding validation?
Consider this fiddle: http://jsfiddle.net/yWGK4/
<form action="#" method="post">
<div id="parent">
<div class="child">
<input type="checkbox" name="box1[]" value="1" /> 1
<input type="checkbox" name="box1[]" value="2" /> 2
<input type="checkbox" name="box1[]" value="3" /> 3
</div>
</div>
</form>
<button id="addBoxes">Add Boxes</button>
<script>
$(function() {
var parentdiv = $('#parent');
var m = $('#parent div.child').size() + 1;
$('#addBoxes').on('click', function() {
$('<div class="child"><input type="checkbox" name="box'+m+'[]" value="1" /> 1 <input type="checkbox" name="box'+m+'[]" value="2" /> 2 <input type="checkbox" name="box'+m+'[]" value="3" /> 3 </div>').appendTo(parentdiv);
m++;
return false;
});
});
</script>
On that form I'm adding new checkbox groups, and want to make sure at least one box from each group is checked (not one box across all groups). Anyone got any clever methods? Everything I've looked at would get very complicated due to the dynamically added fields.
It doesn't matter if the checkboxes are dynamic when validating on submit etc. so something like this would check if at least one checkbox per .child is checked :
$('form').on('submit', function(e) {
e.preventDefault();
var valid = true;
$('.child').each(function() {
if ( ! $('[type="checkbox"]:checked', this).length ) // no box checked
valid = false;
});
if (valid) {
this.submit();
}else{
alert('error');
}
});
FIDDLE
If you want to check it using jQuery you can use `.each()
$(".child").each(function(){
var $this = $(this);
var checked = $this.find("input:checked");
if( checked.lenght == 0 ) {
alert("This group is not valid");
}
});
You can find more about this jQuery functions in this links:
each()
find()
here's what I came up with. Basically you loop over the .child groups and test if they have a checkbox in the checked state..
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});

How to automatically uncheck a checkbox if another checkbox is checked through javascript?

I have a checkbox Birthdate which shows the mm/dd only.And below it there is another checkbox called ShowYear which shows the year and this checkbox is only visible if the Bithdate checkbox is checked.
Now I want to uncheck the ShowYear checkbox automatically if the Birthdate checkbox is
unchecked through javascript.
<input id="cbxBirthDate" type="checkbox" onClick="javascript:uncheckShowYear(this);" />
<input id="cbxShowYear" type="checkbox" />
<script language="javascript" type="text/javascript">
function uncheckShowYear(obj)
{
if (obj.checked == false)
{
document.getElementById("cbxShowYear").checked = false;
}
}
</script>
First, give your check boxes ids eg:
<input type="checkbox" id="birth" />
<input type="checkbox" id="year" />
Javascript:
<script type="text/javascript">
window.onload = function(){
var birth = document.getElementById('birth');
var year = document.getElementById('year');
if (birth.checked == false)
{
year.checked = false;
}
}
</script>
If you are using jquery than
$(document).ready( function a()
{
if ( $('#birth').is(':checked'))
{
$('#year').attr('checked', false);
}
});

Categories

Resources