Attach a checkbox javascript to a class - javascript

I have done 7 check boxes and code them to only one should be checked, and here is the code:
$j(document).ready(function(){
$j(':checkbox').bind('change', function() {
var thisClass = $j(this).attr('class');
if ($j(this).attr('checked')) {
$j(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$j(this).attr('checked', false);
$j('.first-image').show();
$j('.hide-onload').hide();
}
});
});
and I had to create another 2 check boxes in the same page to choose between "yes" or "no" and they have another class
everything is fine except when I check the "Yes" "No" boxes it should not uncheck the first checked box because it is in different class.
The question is: How to make the code I have attach to work only with the class of the first 7 check boxes and make another one for the "Yes" "No" check boxes.
I hope I was clear enough, and here is the page link I am working on it that explains the problem http://www.cabas-durables.fr/magento/index.php/custom-contact/
Thank you in advance ....

You can separate your responsabilities with two additional classes:
$j('.normal-checkboxes:checkbox').bind(...);
$j('.yes-no:checkbox').bind(...);
And then wrap your checkboxes like this:
<div class="normal-checkboxes">
<input type="checkbox">
<input type="checkbox">
</div>
<div class="yes-no">
<input type="checkbox">
<input type="checkbox">
</div>
EDIT:
$j(document).ready(function(){
// When clicking a .normal-checkboxes..
$j('.normal-checkboxes:checkbox').bind('click', function() {
// Remove the property checked for all normal-checkboxes
$('.normal-checkboxes:checkbox').prop('checked', false);
// Add the property checked to the clicked one
$(this).prop('checked', true);
});
});

Related

Show div on checkbox check and hide it when unchecked (even on load because localstorage)

So the page must show a div if a checkbox is checked, and hide it when it is unchecked. But I am using localstorage so it shouldn't hide on load of the page but only when it is unchecked. If it is possible, it should be usable for a lot of checkboxes (37 exactly).
My Code:
HTML:
<div id="mob1-div" class="row hide one">Mobilisern1</div>
<div id="mob2-div" class="row hide-div">Mobilisern2</div>
<div id="mob1" class="targetDiv">Mobiliseren 1<input type="checkbox" class="checkbox chk" value="one" data-ptag="mob1-div" store="checkbox1"/></div>
<div id="mob2" class="targetDiv">Mobiliseren 2<input type="checkbox" class="checkbox" data-ptag="mob2-div" store="checkbox2"/></div>
Javascript:
$(function() {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
});
$(function(){
$(".chk").on('change',function(){
var self=$(this);
var aData= self.attr("value");
$("."+aData).toggleClass('hide')
});
});
The problem with this code is that when you check the box the div shows, but if you reload the page the box is still checked. Although, the div isn't visible anymore.
Your issue seems to be centered around the fact that your second checkbox did not specify a value attribute (which all checkboxes need to have for them to make any sense).
I made a few adjustments to your code to make it more valid and compact (replaced store with data-store, used a ternary operator instead of if/then, combined the two document.ready functions into one, and changed your for loop to a forEach). These changes aren't part of the issue, but they do allow for your code to be more brief, which aids in troubleshooting.
localStorage doesn't work in the Stack Overflow snippets, but a working version can be seen in this Fiddle.

Multiple conditions on single checkbox

I wanted to have a single checkbox in a form but i need to implement multiple scenarios but not sure if this is possible using a single checkbox or if i need radio buttons . Please advise
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
not sure if this is possible using a single checkbox
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
if the requirements 1/2/3 can be met using a single checkbox .The reason i ask is a single checkbox can hold only one value and if there is a way i can alter the value in Jquery dynamically still satisfying all the requirements.
Yes, it is possible. You can create an object having properties set to selectors :checked, :not(:checked, :hidden), :hidden; with corresponding values set to yes, no, blank. Set variable at change event handler using for..in loop, .is()
var obj = {
":checked": "yes",
":not(:checked, :hidden)": "no",
":hidden": "blank"
};
var curr;
$(":checkbox").change(function() {
for (var prop in obj) {
if ($(this).is(prop)) {
curr = obj[prop]; break;
}
}
// do stuff with `curr`
console.log(curr);
});
// check `:hidden`
$(":checkbox").prop("hidden", true)
.change() // `curr` should log `blank`
.prop("hidden", false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="checkbox" />
I have created one sample onchange function where you can handle mutiple events
codepen URL for reference:
http://codepen.io/nagasai/pen/xOGNYW
<input type="checkbox" id="checkTest" onchange="myFunction()">
<input type="text" id="myText" value="checked">
#myText
{
display:none;
}
function myFunction() {
if (document.getElementById("checkTest").checked) {
document.getElementById("myText").style.display = "block";
} else {
document.getElementById("myText").style.display = "none";
}
}

Get the first input checked

I'm trying to set the first input element in
<div class="containerplaatje klein">
<div class=slides>
<input...
"checked" and remove the "checked" status from all others.
The catch is:
Every time i click on a another container it has to set the first input element in that container to "Checked" and release every other.
See fiddle below:
https://jsfiddle.net/qa6not7w/
I thought this one was close, but I still got a failure:
$(document).ready(function info(){
$(".klein").click(function(){
if ($(this).hasClass("containerplaatje")) {
$(this).removeClass("containerplaatje");
$(".containerplaatje2").addClass("containerplaatje");
$(".containerplaatje2").removeClass("containerplaatje2");
$(this).addClass("containerplaatje2");
$(":input").attr ('checked', false);
/*$('input:radio[name=radio-btn][id=img-1]').attr('checked',true);*/
}
});
This sets the checkedness state of all radios to false, and then the first one to true:
$('input[type=radio]').prop('checked', false)[0].checked = true;
$('input[type=radio]').prop('checked', false)[0].checked = true;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" />
<input type="radio" checked />
<input type="radio" />
Note the use of prop in jQuery and properties in vanilla-js, instead of attr in jQuery and setAttribute in vanilla-js.
This did it for me:
$('input[type=radio]').prop('checked', false);
$(this).find('input[type=radio]').filter(':first').prop('checked', true);

Javascript/jQuery issue

I'm trying to make radio buttons that when you have them active, it displays a dropdown. I can already make it display, but when I click on another radio button, it shows one, but doesn't hide the other...
Code:
<input type='radio' name='op' onchange='$("#ban_length").fadeToggle();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeToggle();'/>
JavaScript section:
$(document).ready(function() {
$('#op1').change(function(){
$("#ban_length").fadeIn();
$("#rank_list").fadeOut();
});
$('#op2').change(function(){
$("#ban_length").fadeOut();
$("#rank_list").fadeIn();
});
});
HTML:
<input type='radio' name='op' id='op1'/>
<input type='radio' name='op' id='op2'/>
<div id="ban_length">demo</div>
<div id="rank_list">demo</div>
Demo:
http://jsfiddle.net/b2UPt/1/
<input type='radio' name='op' onchange='$("#ban_length").fadeIn();$("#rank_list").fadeOut();'/>
<input type='radio' name='op' onchange='$("#rank_list").fadeIn();$("#ban_length").fadeOut();'/>
Though I would suggest removing the javascript from the elements themselves, giving them ids and adding the javascript to a separate script with $(theID).change(function(){....
Alternatively, you can use hide instead of fadeOut if you would like them to hide immediately.
And one last suggestion. If there are many of these and not just 2, I would add a shared class to each of the elements you are fading in. Then instead of hide on each element, just call $(".className").hide() to hide any that might be visible.
The change event only fires on the element that was clicked (i.e. the radio button that is now enabled). It isn't fired when a radio button is automatically disabled.
So you need to check all the radio buttons every time one of them triggers the change event. You need to be able to tell them apart, though, so start by giving them ids:
<input type="radio" name="op" id="radio_ban_length" />
<input type="radio" name="op" id="radio_rank_list" />
After that, you can use them to toggle the correct dropdowns:
$('input:radio').change(function() {
var id = $(this).attr("id");
if (id === "radio_ban_length") {
$("ban_length").fadeIn();
$("rank_list").fadeOut();
} else {
$("rank_list").fadeIn();
$("ban_length").fadeOut();
}
});
Alternatively, if you like a challenge or if you might have more than two radio's, you could use filter() and :checked to do something like this:
function getDropdownId(radioId) {
return '#' + radioId.replace(/^radio_/, '');
}
var radios = $('input:radio');
radios.change(function() {
// Checked radio's:
radios.filter(':checked').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeIn();
});
// Unchecked radio's:
radios.filter(':not(:checked)').each(function(){
var id = getDropdownId($(this).attr('id'));
$(id).fadeOut();
});
});
Note that this method does rely on the id's of the radio buttons matching those of the dropdowns (e.g. radio_ban_length for ban_length).
Update: here is a live example: http://jsfiddle.net/55ANB/1/
add id="ban" and id="rank" to your radios
in your jquery section, add the click handler to the radio buttons
$(':radio').click(function() {
if ($(this).attr("id") == "ban") $("ban_length").fadeToggle();
if ($(this).attr("id") == "rank") $("rank_length").fadeToggle();
});

show hide content depending if a checkbox is checked

I'm pretty new to jquery so I'm proud of myself for what I've figured out so far. What I'm trying to do is show/hide a list of options depending on the approprate check box status. Eveything is working just fine but I can't figure out how to check to see if a check box is checked on load I know I should be able to use is.checked right now I have this javascript
$('.wpbook_hidden').css({
'display': 'none'
});
$(':checkbox').change(function() {
var option = 'wpbook_option_' + $(this).attr('id');
if ($('.' + option).css('display') == 'none') {
$('.' + option).fadeIn();
}
else {
$('.' + option).fadeOut();
}
});
Which fades in and out a class depending on the status of the checkbox. This is my html
<input type="checkbox" id="set_1" checked> click to show text1
<p class = "wpbook_hidden wpbook_option_set_1"> This is option one</p>
<p class = "wpbook_hidden wpbook_option_set_1"> This is another option one</p>
<input type="checkbox" id="set_2"> click to show text1
<p class = "wpbook_hidden wpbook_option_set_2"> This is option two</p>
The two problems I have are that the content with the .wpbook_hidden class is always hidden and if the checkbox is checked on load the content should load.
If someone could figure out how to check the status of the box on load that would be much appriciated feel free to play with this jfiddle http://jsfiddle.net/MH8e4/3/
you can use :checked as a selector. like this,
alert($(':checkbox:checked').attr('id'));
updated fiddle
or if you want to check the state of a particular checkbox, it would be something like this
alert($('#set_1')[0].checked);
updated fiddle
for the comment below, I have edited your code and now looks like this.
$('.wpbook_hidden').hide();
$(':checkbox').change(function() {
changeCheck(this);
});
$(':checkbox:checked').each(function(){ // on page load, get the checked checkbox.
changeCheck(this); // apply function same as what is in .change()
});
function changeCheck(x) {
var option = 'wpbook_option_' + $(x).attr('id');
if ($('.' + option).is(':visible')) { // I'm not sure about my if here.
$('.' + option).fadeOut(); // if necessary try exchanging the fadeOut() and fadeIn()
}
else {
$('.' + option).fadeIn();
}
}
#updated fiddle
to checkout if a checkbox is checked you can use the following code :
$(':checkbox').change(function() {
if ( $(this).checked == true ){
//your code here
}
});
Try this:
$("input[type=checkbox]:checked").each(fun....

Categories

Resources