javascript - onchange/onclick function not working on checkbox - javascript

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.

Related

Jquery onclick function called two time on dynamically added button element

I have created a code on my HTML page that their multiple checkboxes and created one button dynamically in js snippet for performing some event, but when I clicked on the button to perform that even that, then it's making calls to that event snippet two times. I wanted to know how to add the event to that button.
Here is the js code:-
$(".panel-body").on("click", '#select_none', function(event) {
$("input[name='nodelevel']:checkbox").each(function() {
this.checked = false;
});
});
Make sure there is only one parent with .panel-body class name. maybe there is two of .panel-body and it makes this happen. like this:
<div class="panel-body">
...
<div class="panel-body">
...
<!-- your selectors -->
</div>
</div>
try stoppropagation to avoid second parent event listener call:
$(".panel-body").on("click", '#select_none', function(event) {
event.stopPropagation();
$("input[name='nodelevel']:checkbox").each(function() {
this.checked = false;
});
});
EDIT : and of course you can add listener to document instead of .panel-body :)
Example:
<input class="itemClass" type="checkbox" name="Items" value="Bike"> I have a bike<br>
<input class="itemClass" type="checkbox" name="Items" value="Car" checked> I have a car<br>
<button name="submit" onclick="getValue()" value="Submit">
Then:
function getValue() {
var id;
var name;
var temp = [];
$('.itemClass').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
console.log(sThisVal);
if (this.checked) {
// $("input[name=Items]:checked").map(function () {
temp.push(sThisVal);
}
});
console.log(temp);
$('.itemCheckboxClass').prop('checked', false);
}

Hiding div class with javascript

I'm wanting to have checkboxes hide and show a div class.
So far i have the code hiding the div but not showing it. Which i know i've done wrong somehow! i do have multiple checkboxes
heres my code
<script type="text/javascript">
function show(target) {
document.getElementById(target).style.display = 'block';
}
function hide(target) {
document.getElementById(target).style.display = 'none';
}
</script>
<tr>
<th><input onclick="hide('tester')" type="checkbox" checked>
I know its something to do with the onclick hide. Would it be better to have it as a toggle?
Sam
You need to use a single handler in which based on the checked state you can set the display value like
function showhide(el, target) {
document.getElementById(target).style.display = el.checked ? 'block' : 'none';
}
<input onclick="showhide(this, 'tester')" type="checkbox" checked />
<div id="tester">tester</div>
Using jQuery
$('#mycheckbox').change(function() {
$('#tester').toggle(this.checked)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="mycheckbox" type="checkbox" checked />
<div id="tester">tester</div>
Try this
function toggle(target) {
if(document.getElementById(target).style.display=="block")
document.getElementById(target).style.display = 'none';
else
document.getElementById(target).style.display = 'block';
}
<input onclick="toggle('toggle')" type="checkbox" checked>
<div id="toggle">Show and hide</div>
Try this one:
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
Demo

Control Radio Buttons with a Checkbox

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 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 :)

hiding div based on unchecking checkboxes

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

Categories