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
Related
I'm relatively new to JS and was looking for an article or method in which to accomplish the following - be it a form or just JS. (Would like to avoid PHP.)
I have a series of check boxes call them box 1 - 4, which when any one is checked should either show a div or post text to a particular div on the page.
Example: when box 1 is checked div A posts "Box one has been checked."
I'm not certain how to refine my searches to find an example of what I'm looking for but did find a jsfiddle with a similar technique this posts a textbox under the checkbox when activated.
DEMO
<input id="chk" type="checkbox" value="results" />Results
<div id="formContainer"></div>
var textboxId = 0;
function CreateTextbox() {
var textBox = document.createElement("input");
textBox.setAttribute("type", "textbox");
textBox.setAttribute("id", textboxId);
textboxId++;
return textBox;
}
document.getElementById("chk").onclick = function () {
if (textboxId == 0) {
document.getElementById("formContainer").appendChild(CreateTextbox(textboxId));
textboxId = 1;
} else if (textboxId == 1) {
document.getElementById("formContainer").innerHTML = '';
textboxId = 0;
//The code to remove the previosuly made textbox
}
}
Any direction or code ideas are appreciated. Thanks!
Hope this is what you are expecting.
$('.chkbox').on('click',function(){
if($(this).is(':checked')) //check if checkbox is checked or unchecked
{
$(this).next('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>');
//get detail to add from the clicked checkbox's data-* attribute
}
else
{
$(this).next('.formContainer').html('');
//just empty the html below it
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="chk" data-detail="Box one has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
<input id="chk2" data-detail="Box two has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
<input id="chk3" data-detail="Box three has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
<input id="chk4" data-detail="Box four has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
Add detail for each checkbox in its data-detail property. Refer html above
Extenal Demo
Update
To display all the text in a single div you can just refer the target element as below:
$('.chkbox').on('click',function(){
if($(this).is(':checked'))
{
$('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>'); //directly refer the element
}
else
{
$('.formContainer').html('');
}
});
Updated demo
Not sure if this is what you really need, but this should help you get started, It also requires jquery
HTML
<input class="mychk" type="checkbox" value="Box 1 is Check" />Box 1<br>
<input class="mychk" type="checkbox" value="Box 2 Box is Check" />Box 2<br>
<input class="mychk" type="checkbox" value="Box 3 Box is Check" />Box 3<br>
<input class="mychk" type="checkbox" value="Box 4 Box is Check" />Box 4
<div class="showcheck">I'll Be Overwritten When Checkbox is check</div>
jQuery
(function($) {
//run for each input box
$('.mychk').each( function() {
// detect change action
$(this).change( function() {
// if the checkbox is check
if( $(this).is(':checked') ) {
//insert checkbox value in showcontent div
$('.showcheck').html( $(this).val() );
} else {
// if uncheck, assign default value
$('.showcheck').html( 'Default Content' );
}
});
});
})(jQuery);
Demo here
Pure JavaScript answer:
HTML:
<div id="checkboxes">
<input id="one" type="checkbox"></input>
<input id="two" type="checkbox"></input>
<input id="three" type="checkbox"></input>
</div>
<div id="answer"></div>
JS:
[].forEach.call(document.getElementById("checkboxes").children, function(element) {
element.onclick = function () {
document.getElementById("answer").innerHTML = element.id + " " + element.checked;
}
});
JSfidle
I am trying to trigger onclick function by checkbox and link. Here is Demo which works fine. But If I make change by writing onclick/onchange inside checkbox its not working.:
<input type="checkbox" id="mycheckbox" onclick="myChange();"/>
If I call like this then it works fine:
<input type="checkbox" id="mycheckbox">
document.getElementById('mycheckbox').onclick = function(){
myChange();
};
Not working :( I wanted to work in Javascript only. Not Jquery What is the reason myChange() not being called from inside input tag
Check Here your updated code works.
function myChange(){
var temp = document.getElementById('mycheckbox');
document.getElementById('container').style.display = temp.checked ? 'block' : 'none';
};
document.getElementById('loginlink').onclick = function(){
if (document.getElementById('mycheckbox').checked) {
document.getElementById('mycheckbox').checked = false ;
myChange();
} else {
document.getElementById('mycheckbox').checked = true ;
myChange();
}
}
#container {
display: none;
}
<div id="container">Check Box is Checked</div>
<br><br>
<label>
<input type="checkbox" id="mycheckbox" onclick="myChange()"/>
Show/hide
<a href="javascript:void(0)" id="loginlink" >Click Me</a>
</label>
Check Fiddle.
I have tried several ways to achieve this, but somehow nothing works for this.
How can I copy the "label text" of respective Radio Button, which is selected by user into the input field (Result Box) in real time?
HTML -
<ul class="gfield_radio" id="input_4_4">
Radio Buttons:
<br />
<li class="gchoice_4_0">
<input name="input_4" type="radio" value="2" id="choice_4_0" class="radio_s" tabindex="4">
<label for="choice_4_0">Hi</label>
</li>
<li class="gchoice_4_1">
<input name="input_4" type="radio" value="4" id="choice_4_1" class="radio_s" tabindex="5">
<label for="choice_4_1">Hello</label>
</li>
<li class="gchoice_4_2">
<input name="input_4" type="radio" value="3" id="choice_4_2" class="radio_s" tabindex="6">
<label for="choice_4_2">Aloha</label>
</li>
</ul>
<br />
<div class="ginput_container">
Result Box:
<br />
<input name="input_3" id="input_4_3" type="text" value="" class="medium" tabindex="3">
</div>
My attempts:
$('input').change(function() {
if (this.checked) {
var response = $('label[for="' + this.id + '"]').html();
alert(response);
}
// also this:
// if ($("input[type='radio'].radio_s").is(':checked')) {
// var card_type = $("input[type='radio'].radio_s:checked").val();
// alert('card_type');
// }
});
You need to traverse the DOM from the radio which was clicked to find the nearest label element.
$('.radio_s').change(function() {
$('#input_4_3').val($(this).closest('li').find('label').text());
});
Example fiddle
You could also use $(this).next('label') however, that relies on the position of the label element not changing. My first example means the label can be anywhere within the same li as the radio button and it will work.
Try this:
$('.radio_s').click(function() {
$("#input_4_3").val($("input:checked" ).next().text());
});
Demo: http://jsfiddle.net/WQyEw/3/
This is a slightly tricky question to answer well. The structure of your HTML implies that there may be more than one of these structures on the page. So you may have more than one set of radio buttons with a corresponding checkbox.
I have put some working code into a jsFiddle.
I made one change: all the code you had in your question is now in <div class="container">. You would need as many of these as you had groups of radio buttons and checkboxes.
You can then have jQuery code like this:
$('ul.gfield_radio').on('change', 'input[type="radio"]', function () {
var label = $('label[for="' + this.id + '"]');
$(this).closest('.container').find('input.medium').val(label.text());
});
This code is not tied to the id values in this particular bit of HTML, but would work as many times as necessary throughout the page.
Why to depend on third party library when you can achieve it with plain javascript:
<script>
document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementsByName('input_4');
for (var i = 0; i < a.length; i++) {
document.getElementsByName('input_4')[i].addEventListener('change', function () {
showValue(this);
}, false);
}
}, false);
function showValue(element) {
alert(element.parentNode.getElementsByTagName('label')[0].innerHTML)
}
</script>
I'm using a CMS that hides form elements behind tags, because of some system quirks I've had to set up a checkbox that controls the radio buttons so if the checkbox is ticked the "yes" radio button is selected if not the "no" is selected. I also want the radio buttons to have option "no" checked by default but I don't have control over the line of code for the radio buttons.
I found some Javascript that does a small part of this but I want to integrate it into the jQuery that displays and hides content when the box is ticked.
Here's what I have so far:
$('#checkbox1').change(function() {
$('#content1').toggle("slow");
});
The Javascript I have is this:
function ticked(){
var ischecked = document.getElementById("checkbox").checked;
var collection = document.getElementById("hideradio").getElementsByTagName('INPUT');
if(ischecked){collection[0].checked = true;}else{collection[0].checked = false;}
}
Can you please help write a version of the Javascript but integrate with my jQuery?
Thanks,
You can try this, I assume your html as like this.
<input type="checkbox" id="checkbox1" /> Check Box
<div id="content1" >
Some Content <br />
Some Content <br />
Some Content <br />
Some Content
</div>
<div id="hideradio">
<input type="radio" name="rgroup" value="yes" /> Yes
<input type="radio" name="rgroup" value="no" /> No
</div>
JQuery
$(function(){
$('#hideradio input[type=radio][value=no]').attr('checked',true);
$('#content1').hide();
});
$('#checkbox1').on('change', function() {
$('#content1').toggle("slow");
var self = this;
if(self.checked)
$('#hideradio input[type=radio][value=yes]').attr('checked',true);
else
$('#hideradio input[type=radio][value=no]').attr('checked',true);
});
A Quick DEMO
Try this code
$(function(){
$('#checkbox1').on('click' , function() {
var isChecked = $(this).is(':checked');
if(isChecked){
$('#radio1').attr('checked' , true);
$('#content1').toggle("slow");
}
else{
$('#radio1').attr('checked' , false);
}
});
});
Check [FIDDLE]
If I don't understand correctly then let me know.
I don't know your HTML code so I provide one
<form>
<input type="checkbox" name="test_ck" id="test_ck" />
<br/>
<input type="radio" name="test_radio" id="test_radio" />
</form>
<div id="content"> A content !!! </div>
and javascript jquery
$(function(){
$("#test_ck").on("change", function(){
$("#test_radio").prop("checked", $(this).is(":checked"));
$("#content").toggle("slow");
});
});
Example -> jsfiddle
UPDATED jsfiddle
http://jsfiddle.net/6wQxw/2/
jsfiddle
$(document).on('change', '#checkbox', function() { toggle(this); });
var toggle = function(obj) {
var checked = $(obj || '#checkbox').is(':checked');
$(':radio[value=no]').prop('checked', !checked);
$(':radio[value=yes]').prop('checked', checked);
$('#content').toggle(checked);
}
toggle();
This is a pure JavaScript solution, no need to use jQuery:
<body>
<label for="a">Male</label>
<input type="radio" id="a">
<br/>
<label for="b">Female</label>
<input type="radio" id="b">
<script type="text/javascript">
var nodes = document.querySelectorAll("input[type=radio]");// get elements
var arr = Array.prototype.slice.call(nodes); // convert nodes to array for use in forEach
arr.forEach(function(obj){
obj.addEventListener("change",function(e){
arr.forEach(function(obj){
obj.checked = false;//make other radio false
});
this.checked = true;// make this radio ture
});
});
</script>
</body>
How to apply checkbox with functions in javascript?
How to hide post/object with specific tags when checkbox is unchecked?
I just need to know how to put functions for the checkbox to be automatically check upon opening the page and the checkbox to hide posts/objects with a specific tag on them. Is it correct to apply--
display:none
or--
.structural {
position:absolute;
left:-9999px;
}
--that I've found during research?
This was as far as I could go considering my lack of skills:
<input
type="checkbox"
name="mycheckbox"
value="yes"
onclick=" CheckboxChecked(this.checked,'checkboxdiv')"
</div>
</div>
<script type="text/javascript">
CheckboxChecked(document.myform.mycheckbox.checked,'checkboxdiv');
</script>
If I understood your question correctly, you are attempting to hide/show a group of elements when a checkbox is checked/unchecked. This should be enough to get you going:
http://jsfiddle.net/HsCVq/
HTML:
<div class="hideWhenChecked">hide text</div>
<div>dont hide text</div>
<div class="hideWhenChecked">hide text</div>
<div>dont hide text</div>
<br />
<input type="checkbox" id="myCheckBox" />
JavaScript:
document.getElementById('myCheckBox').addEventListener('click', function () {
var checked = this.checked;
var elementsToHide = document.getElementsByClassName('hideWhenChecked');
if (checked) {
// hide each element
} else {
// show each element
}
});
I'd suggest looking into a javascript framework such as jQuery to make this code a lot simpler.
With jQuery
Something like this is pretty trivial with jQuery:
$("form").on("click", ":checkbox[name^='toggle_']", function(event){
$( "#" + event.target.name.split('_')[1] )
.toggle( event.target.checked );
});
But you shouldn't use jQuery just for something like this - that would be overkill.
Old-fashioned JavaScript, the way your Grandfather did it.
Here's a quick implementation (tested in IE7+). It works by extracting the corresponding element to hide from the name of the checkbox being clicked.
<form name="myform">
<input name="toggle_checkBox" type="checkbox" checked />
<div id="checkBox">
If checked, you'll see me.
</div>
</form>
This checkbox, when clicked will hide the DIV below it.
var myform = document.forms.myform;
var inputs = myform.getElementsByTagName("input");
function toggleElement () {
var e = event.target || window.event.srcElement;
var display = e.checked ? "" : "none" ;
document.getElementById( e.name.split('_')[1] ).style.display = display;
}
for ( var i = 0; i < inputs.length; i++ ) {
var chk = inputs[i];
if ( chk.type == "checkbox" && /^toggle_/.test( chk.name ) ) {
if ( chk.addEventListener ) {
chk.addEventListener("click", toggleElement, false);
} else if ( chk.attachEvent ) {
chk.attachEvent("onclick", toggleElement);
}
}
}
Demo: http://jsbin.com/ibicul/5
Have a look at this
HTML:
<form>
<!-- for keeping checkbox checked when page loads use checked="checked" --->
<input type="checkbox" name="check" onclick="toggle(this.form.check);" checked="checked">
<input type="checkbox" name="check1"/><br>
<br>
</form>
<!-- the id of this element is used in script to set visibility --->
<div id="text" style="visibility:hidden">
My visibility is based on checkbox selection
</div>
Script
<script>
function toggle(check)
{ if(!check.checked)
{
document.getElementById('text').style.visibility='visible';
}
else
{
document.getElementById('text').style.visibility='hidden';
}
}
</script>
This should work :)