I want to set values of selected checkbox to text input
For example: see this image Click
Problem is when i click "Select All" checkbox "child" checkboxes are checked but value not set in textbox and values set when i uncheck the "Select All" checkbox
I want to get checkbox values in array so i am using map function,
Please see jquery on fiddle
fiddle here
HTML CODE
<form action="" id="form">
<input type="checkbox" id="selectAll">
<label for="selectAll">Select All</label><br>
<div class="child">
<input type="checkbox" class="selectCb" value="1" id="one">
<label for="one">One</label><br>
<input type="checkbox" id="two" class="selectCb" value="2">
<label for="two">Two</label><br>
<input type="checkbox" class="selectCb" value="3" id="three">
<label for="three">Three</label><br>
</div>
<input type="text" id="textBox">
</form>
EDIT
Both codes are working
$(document).on("click", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
Check on fiddle fiddle 2
$(document).on("change", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']").prop('checked', this.checked).map(function () {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
check on fiddle fiddle 3
Now my doubt is which one is better and correct ?
because i want to set background image for all checkbox, so I hide all checkboxes using css
#form input[type="checkbox"] {
display: none;
}
And set background image for checkbox using following css code
Set Background for "Select All" Checkbox
input[type="checkbox"]#selectAll + label#selectAllLbl::before {
content: '';
background: url('http://s30.postimg.org/uhql9zd5p/chk_uncheck.png') no-repeat;
height: 22px;
width: 22px;
display: inline-block;
margin-right: 10px;
}
input[type="checkbox"]#selectAll:checked + label#selectAllLbl::before {
content: '';
background: url('http://s9.postimg.org/6k81psojf/chk_enabled.png') no-repeat;
}
Set Background for "child" Check boxes
input[type="checkbox"].selectCb + label.childLbl::before {
content: '';
background: url('http://s30.postimg.org/uhql9zd5p/chk_uncheck.png') no-repeat;
height: 22px;
width: 22px;
display: inline-block;
margin-right: 10px;
}
input[type="checkbox"].selectCb:checked + label.childLbl::before {
content: '';
background: url('http://s9.postimg.org/6k81psojf/chk_enabled.png') no-repeat;
}
so is it right ? to use hidden checkbox id and class in jquery
<input type="checkbox" id="selectAll">
<input type="checkbox" class="selectCb" value="1" id="one">
Switch change to click in the second argument:
$(document).on("change", ".selectCb", function () {
var values = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(values.join(' '));
});
$(document).on("click", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
If you want the selectAll to toggle the checks on other checkboxes use prop() to do it. Using this.checked will indicate whether to check or uncheck them
$(document).on("change", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']").prop('checked', this.checked).map(function () {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
DEMO
Instead of hiding checkbox you can assign negative margin to it.
Please refer below CSS snippet :
#form {overflow:hidden}
#form input[type="checkbox"]{
margin-left:-25px
}
Also want to repeat what jonmrich has already said to switch "change to click" in the second argument for "#selectAll" checkbox.
Thanks
Related
I have an input element with a checkbox:
<input type="checkbox" id="ID1" name="ID1" checked>
Somwhere else (outside the input field), I would like to have a text, which is changing its appearence according the check status of the input element with the ID1.
Something like:
<span for id='ID1' class='Class1'>TEST</span>
How do I get a dependency between the text and the status of the input field and how is it possible to change Class1 to Class2 by checking and unchecking the checkbox? The class changes the background color of the Text. I know how to do this inside the same element. But having two different elements? Or is it possible to access the class via the ID of the input element, due to the "for" statement? I am working with javascript.
Thanks for any help!
Add an attribute to the checkbox with the ID of the related span.
document.querySelector("#ID1").addEventListener("click", function() {
let rel = document.getElementById(this.getAttribute("rel"));
if (rel) {
if (this.checked) {
rel.classList.add("Class1");
rel.classList.remove("Class2");
} else {
rel.classList.add("Class2");
rel.classList.remove("Class1");
}
}
});
.Class1 {
background-color: red;
}
.Class2 {
background-color: blue;
}
<input type="checkbox" id="ID1" name="ID1" checked rel="span1">
<span id="span1" class='Class1'>TEST</span>
First : you can't/shouldn't have two element with same Id
const checkbox = document.getElementById("ID1");
const span = document.getElementById("SpanID1");
checkbox.addEventListener('change', function() {
if (this.checked) {
span.innerHtml= 'TEST Checked'
} else {
span.innerHtml= 'TEST Unchecked'
}
});
If you want a CSS solution, you can target the input box and use the :checked selector followed by + then the adjacent element.
CSS: element+element [div + p] Selects the first <p> element that is placed immediately after <div> elements
.Class1 {
background-color: yellow
}
#ID1:checked + .Class1 {
background-color: skyblue
}
<input type="checkbox" id="ID1" name="ID1" checked>
<span for id='ID1' class='Class1'>TEST</span>
Check here to know more about the different CSS selectors.
I want to get appear a div box when user checks any first checkbox.
I have also tried following codes:
JQ Codes:
$('#checkbox').change(function() {
if ($(this:first).is(':checked')) {
console.log('Checked');
} else {
console.log('Unchecked');
}
});
HTML Codes:
<?php foreach ($band_data as $row) { ?>
<fieldset>
<legend>Text</legend>
<input type="checkbox" class="scheme-check" id="checkscheme" name="checkme">
</fieldset>
<?php } ?>
<!--Div to be shown on hide-->
<div class=counter-box></div>
But not working please tell me any correct method to do so.
First of all thanks for instant help; I should mention the case properly to avoid misunderstanding. I use those new codes but due to 'toggle' event its hiding when I checked/unchecked any checkbox. I want to show box till last checkbox is checked and will be hide it on last uncheck.
Take a look at this: http://jsfiddle.net/nq65qnr0/
JavaScript:
// Bind the change event to the common class of all the checkboxes.
$('.scheme-check').change(function(){
if($(".scheme-check:checked").length>1) return; // If not the first one, then do nothing.
if($(this).is(':checked')) {
console.log('Checked');
//show hide div here
}
else {
console.log('Unchecked');
}
});
Assuming your HTML generated to be like this:
<input type="checkbox" class="scheme-check" id="checkscheme1" name="checkme">
<input type="checkbox" class="scheme-check" id="checkscheme2" name="checkme">
<input type="checkbox" class="scheme-check" id="checkscheme3" name="checkme">
.....
(HTML)
<input class="check-box" type="checkbox">Check Me</input>
<input class="check-box" type="checkbox">Check Me</input>
<input class="check-box" type="checkbox">Check Me</input>
<input class="check-box" type="checkbox">Check Me</input>
<div class="hidden"></div>
(CSS)
.hidden {
display: none;
height: 100px;
width: 100px;
background-color: blue;
}
(JavaScript)
$(document).ready(function() {
checkBox();
});
function checkBox() {
$('.check-box').on("change", function() {
$('.hidden').toggle();
});
}
Whatever you are doing is correct but use class instead of id
$('.scheme-check').change(function() {
if ($(this).is(':checked')) {
console.log('Checked');
} else {
console.log('Unchecked');
}
});
In my page there are several Div that hold rating point and also some checkbox. Basically i want based on checkbox selection Div rating will show.i don't know how do that through jquery.
for Example
<div id="ratingbox">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>
<div id="chkbox">
<input type="checkbox" class="ratingCheckbox" value="1" onclick="selection()">1
<input type="checkbox" class="ratingCheckbox" value="2" onclick="selection()">2
<input type="checkbox" class="ratingCheckbox" value="3" onclick="selection()">3
<input type="checkbox" class="ratingCheckbox" value="4" onclick="selection()">4
<input type="checkbox" class="ratingCheckbox" value="5" onclick="selection()">5</div>
LINK
if checkbox 1 is checked, span with value 1 will be visible and all others will be hidden, If checkbox 1 and 4 are checked span with value 1 and span with value 4 are only visible and rest are hidden. if no checkbox is checked then all are visible.
You can do something like this
$('.ratingCheckbox').on('click', function(){
$('span:contains('+this.value+')').toggle();
});
And hide the spans by default with this in css display: none;
Check the demo here http://jsfiddle.net/dhirajbodicherla/dnyfmhyx/4/
Update
Try something like this
var checkbox = $('.ratingCheckbox').on('change', function () {
var val = checkbox.map(function (index, el) {
return (el.checked) ? +$(el).val() : undefined;
}).get(); // this will get the list of checked values in an array like this - [1,4]
if (val.length > 0) { // if at least one checkbox is checked
$('span').hide(); // hide all
$('span').filter(function (index, el) { // this will get all the spans which have value 1 and 4 from the above array
return $.inArray(+$(el).text(), val) != -1 ? el : undefined;
}).show(); // show the ones that are checked
} else {
$('span').show(); // if no checkbox is checked show everything
}
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/dnyfmhyx/5/
I give the spans display: none; when the corresponding checkbox is check I add .visible class to them:
#ratingbox > span {
/* other styles */
display: none;
}
#ratingbox > span.visible {
display:inline-block;
}
In the jQuery part we just need to get the value of the new changed checkbox and toggle the visible class of corresponding spans (I used onchange instead of onclick):
$('#chkbox > input[type=checkbox]').on('change', function() {
var val = $(this).val();
$('#ratingbox > span').each(function() {
if($(this).text() == val)
$(this).toggleClass('visible');
});
});
jsfiddle DEMO
I am generating 5 checkboxes dynamically. I can select upto 3 checkboxes. Once 3 checkboxes are selected, If I try to select one more checkbox it should give an alert and once i click ok on the alert box the fourth checkbox that I have selected should be unchecked.
Code I am using for generating checkboxes dynamically
$("#catalog_table").append('<tr><td style="width:10%; background-color:#fcfbf6; font-family:Proxima Nova Regular; font-size:11pt; font-color:#443b33;text-align: center;">'+productCatalog[i].productCode+'</td><td style="width:10%; background-color:#fcfbf6; text-align: center;font-family:Proxima Nova Regular; font-size:11pt; font-color:#443b33;">'+productCatalog[i].productName
+'</td><td style="width:10%; background-color:#fcfbf6; font-family:Proxima Nova Regular; font-size:11pt; font-color:#443b33; text-align: center;"><input type="checkbox" style="background-color:#fcfbf6;" name="chkOccupancy" class="chkbox" value='+productCatalog[i].productCode+'></td></tr>');
I tried number of ways...but all are getting unchecked.Can anyone tell me how to do this.
This should work for you
$(document).ready(function () {
$(':checkbox').click(function() {
if($(':checkbox:checked').length > 3){
alert('you can not check more than 3 checkboxes');
$(this).prop('checked',false);
}
});
})
Try this example:
$(function () {
$(document).on('change', 'input[name=chkOccupancy]', function (e) {
var chk = $(this);
var cnt = $('input[name=chkOccupancy]:checked').length;
if(3 < cnt) {
chk.prop('checked', false);
alert('Not more than 3 !');
}
e.stopPropagation();
});
});
As an alternative, here's a non–jQuery option. You can put a single listener on an an ancestor element, say a div, and prevent a fourth checkbox from being checked:
function checkCBs(e) {
var el = e.target;
if (el.type == 'checkbox' && document.querySelectorAll('input:checked').length > 3) {
el.checked = false;
}
}
You might want to qualify the selector to keep it within the div or for inputs with a particular class. Sample markup:
<div onclick="checkCBs(event)">
<label for="cb0">stuff<input type="checkbox" name="cb0" id="cb0">0</label><br>
<label for="cb1">stuff<input type="checkbox" name="cb1" id="cb1">1</label><br>
<label for="cb2">stuff<input type="checkbox" name="cb2" id="cb2">2</label><br>
<label for="cb3">stuff<input type="checkbox" name="cb3" id="cb3">3</label><br>
<label for="cb4">stuff<input type="checkbox" name="cb4" id="cb4">4</label><br>
</div>
I have multiple checkboxes in a form. Based on clicking those checkboxes, I show a div section. But if I uncheck even one checkbox, that div section gets hidden. How do I make sure that div section is hidden only if all checkboxes are unchecked. Crude way can be to write my own 'display' method which will check if all checkboxes are unchecked and then hide the div section. Any easier solution??
HTML:
<input type="checkbox" class="group" name="check1">
<input type="checkbox" class="group" name="check2">
<input type="checkbox" class="group" name="check3">
<input type="checkbox" class="group" name="check4">
jQuery:
$(function() {
var $checks = $('input:checkbox.group');
$checks.click(function() {
if($checks.filter(':checked').length == 0) {
$('#div').hide();
} else {
$('#div').show();
}
});
});
The following code will show the div if one or more checkboxes has been checked:
jQuery
Version 1:
$("input[name='mycheckboxes']").change(function() {
$("#showme").toggle($("input[name='mycheckboxes']:checked").length>0);
});
Version 2 (more efficient):
var MyCheckboxes=$("input[name='mycheckboxes']");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<input type="checkbox" name="mycheckboxes" />
<div id="showme" style="display: none">Show me</div>
Code in action (Version 1).
Code in action (Version 2).
--- Different Checkbox Names Version ---
For different named checkboxes, wrap them in a DIV with an identifier. E.g.
jQuery
var MyCheckboxes=$("#checkboxgroup :checkbox");
MyCheckboxes.change(function() {
$("#showme").toggle(MyCheckboxes.is(":checked"));
});
HTML
<div id="checkboxgroup">
<input type="checkbox" name="mycheckbox1" />
<input type="checkbox" name="mycheckbox2" />
<input type="checkbox" name="mycheckbox3" />
<input type="checkbox" name="mycheckbox4" />
</div>
<div id="showme" style="display: none">Show me</div>
This code in action.
Not really, you need Javascript for this one... Or maybe... Let's say:
<html>
<head>
<style type="text/css">
#input_container > input + input + input + div {display:none}
#input_container > input:checked + input:checked + input:checked + div {display:block}
</style>
</head>
<div id="input_container">
<input type="checkbox">blah1
<input type="checkbox">blah2
<input type="checkbox">blah3
<div>To show/hide</div>
</div>
</body>
</html>
I'd create a function that uses a variable that tracks the number of checkboxes checked:
var numberOfChecks = 0;
function display(ev) {
var e = ev||window.event;
if (this.checked) {
numberOfChecks++;
} else {
numberOfChecks--;
}
if (!numberOfChecks) {
//hide div code
} else {
//display div code
}
}
Use that function for each onClick event for every checkbox. In the ideal world this would be done inside some initialization function so that numberOfChecks and display aren't in the global namespace.
Plain Javascript:
HTML
<div id="checkboxes">
<input type="checkbox" name="check1">
<input type="checkbox" name="check2">
<input type="checkbox" name="check3">
<input type="checkbox" name="check4">
</div>
<div id="hiddendiv"><!-- more stuff --></div>
Javascript
(function() { //Create clousre to hide the checked variable
var checked = 0;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].type == 'checkbox') {
if (inputs[i].checked) checked++; //Count checkboxes that might be checked on page load
inputs[i].onchange = function() {
checked += this.checked ? 1 : -1;
var hiddendiv = document.getElementById('hiddendiv');
if (!checked) hiddendiv.style.display = "none";
else hiddendiv.style.display = "";
};
}
}
}());
The other option is to simply iterate through each checkbox every time the change event is fired rather than relying on counting, which is probably more error prone. Obviously jQuery is more concise, but a little verbosity never hurt anyone.
function toggleCheckbox(id) {
if ($("input[id=" + id + "]").is(':checked')) {
$( "#"+id ).prop( "checked", false );
} else {
$( "#"+id ).prop( "checked", true );
}
}
Just pass the id of your checkbox