When click on button, show divs with checked checkbox using JQuery - javascript

I want to use JQuery on my Coldfusion application for showing/hiding div elements with checkbox checked/unchecked within the div.
Basically, in a view I show multiple divs elements, every div have also more divs inside, one of these internal divs contains an input type checkbox that could come checked or unchecked.
I also have three buttons in that view 'Active, Inactive, All'. When clicking on Active I want to show all div elements with checkbox checked, not showing the unchecked, and the other way around when clicking on Inactive.
<div class="btn-group ">
<button id="actives" type="button">Actives</button>
<button id="inactives" type="button">Inactives</button>
<button id="all" type="button">All</button>
</div>
<div id="apiDiv">
<cfloop array="#apis#" index="api">
<div class="card card-found">
<div class="card-header">
<cfif Len(api.iconClass)>
<i class="fa fa-fw #api.iconClass#"></i>
</cfif>
#structKeyExists( api, "name" ) ? api.name : api.id#
</div>
<div class="card-body">
<p>#api.description#</p>
</div>
<div class="card-button">
<input class="#inputClass# ace ace-switch ace-switch-3" name="#inputName#" id="#inputId#-#api.id#" type="checkbox" value="#HtmlEditFormat( api.id )#"<cfif ListFindNoCase( value, api.id )> checked="checked"</cfif> tabindex="#getNextTabIndex()#">
<span class="lbl"></span>
</div>
</div>
</cfloop>
</div>
I´m not an expert at all with JQuery. The only thing I have done is what follows and I do not know whether if is a good beggining or not:
$("#actives").click(function (e) {
$("#apiDiv .card").filter(function() {
<!--- code here --->
});
});
Someone please that can help me with it? Thanks a lot in advance!

After your CF code executes, it will generate a .card for each loop iteration of your apis array. So you jQuery code will need a click handler for the #actives button and that will loop through each() iteration of the checkboxes to determine the checked/unchecked state. At that point find the closest() ancestor .card and show()/hide() the .card depending upon the checkbox state.
$("#actives").click(function (e) {
$('input[type=checkbox]').each(function() {
if (this.checked) {
$(this).closest(".card").show();
} else {
$(this).closest(".card").hide();
}
});
});

If you want to do it with jQuery code:
$('#actives').click(function(){
$('#apiDiv').show();
});
Working Fiddle

The code you are probably looking for is in these event handlers for your buttons:
function activesHandler() {
jQuery(".card-button > input:checked").parents(".card.card-found").show();
jQuery(".card-button > input:not(:checked)").parents(".card.card-found").hide();
}
function inactivesHandler() {
jQuery(".card-button > input:checked").parents(".card.card-found").hide();
jQuery(".card-button > input:not(:checked)").parents(".card.card-found").show();
}
function allHandler() {
jQuery(".card.card-found").show();
}
jQuery("#actives").click(activesHandler);
jQuery("#inactives").click(inactivesHandler);
jQuery("#all").click(allHandler);
I reproduced some of your ColdFusion by replacing it with JavaScript and provided a demonstration of the above event handlers in this JSFiddle.

Call the checkbox by its id and when it's checked, write a function to display the divs you want to display:
<input type="checkbox" id="check">
$document.getElementById("check").onclick = function(){
$document.getElementById("div_name").style.display="block"; // block displays the div.
}

Related

Hide existing <div> and show previous <div> in multi-branch form

I will start by telling you that this is my very first Javascript program from scratch. I am trying to make a back button that will go to the previously chosen div in a form (hide the current div and show the previous one the user chose).
The form has multiple paths to follow, paths within paths and not all selectors are buttons. There might be an onchange event or a radio button or even text input (text inputs have a next button to click).
I have had it working where it will hide the current div but show all previous chosen divs. It's now working where it hides the current div but shows nothing.
I have read a bunch of postings here and in other forums but have not found what I need yet. Any help would be greatly appreciated.
You can see the actual site here and I have put up a JSfiddle but for some reason I can't get it working there.
Here is the code from the fiddle:
<div>
<form>
<div id="uno" class="showFirst">
<button onclick="hideUno()">First Button</button>
</div>
<div id="dos" class="hideFirst">
<button onclick="hideDos()">Second Button</button>
</div>
<div id="tres" class="hideFirst">
<button onclick="hidetres()">Third Button</button>
</div>
<div id="quattro" class="hideFirst">
<button onclick="hideQuattroUno()">Fourth Button</button>
<button onclick="hideQuattroDos()">Fifth Button</button>
</div>
<div id="branchUno" class="hideFirst">
<p>First Branch</p>
</div>
<div id="branchDos" class="hideFirst">
<p>Second Branch</p>
</div>
</form>
<button id="backButton" onclick="goToPrevious" class="hideFirst">Back</button>
</div>
.hideFirst {
display: none;
}
function goToPrevious() {
var current = $(".chosen").find(":visible");
$(current).hide();
$(current).prev(".chosen").show();
}
function hideUno() {
$("#backButton").toggle();
$("#uno").toggle();
$("#uno").addClass("chosen");
$("#dos").toggle();
}
function hideDos() {
$("#dos").toggle();
$("#dos").addClass("chosen");
$("#tres").toggle();
}
function hideTres() {
$("#tres").toggle();
$("#tres").addClass("chosen");
$("#quattro").toggle();
}
function hideQuattroUno() {
$("#quattro").toggle();
$("#quattro").addClass("chosen");
$("#branchUno").toggle();
}
function hideQuattroDos() {
$("#quattro").toggle();
$("#quattro").addClass("chosen");
$("#branchDos").toggle();
}
Here are a few of the questions I've reviewed here:
retain show / hide div on multistep form
Hide and Show div in same level
how to show previous div of clicked div in angular.js
show div and hide existing div if open with jQuery?
Show one div and hide the previous showing div
I realize it's not the cleanest code, but as I said this is my first and I am trying to cleanup as I go along and learn new things.
You could make a bit of automatization instead of creating onclick events for each button/select separately.
For "Back" functionality, I'd use an array to store elements "on the fly" at each step, instead of checking visibility later on.
I'll make it this way:
Remove CSS rule display:none for hideFirst class (elements will be hidden using jQuery).
Add an class to the buttons/selects/check-boxes/etc... as event inndicator.
Add data-next attribute (to store id of the element which should be shown on click/change)
HTML:
<div id="firstDiv" class="hideFirst">
<button class="my-btn" data-next="#secondDiv" type="button">Show next<button>
</div>
<div id="secondDiv" class="hideFirst">
<select class="my-select" data-next="#thirdDiv">
<option>Helo World</option>
...
</select>
</div>
...
Script:
$(document).ready(function(){
// hide all 'hideFirst' elements, except the first one:
$('.hideFirst:not(:first)').hide();
// declare 'history' variable as an empty array (it will be used to store 'hideFirst' elements for 'Back' functionality):
var history = [];
// click event for the buttons :
$('.my-btn').click(function(e){
// as the button will submit the form if you're not using type="button" attribute, use this:
e.preventDefault();
showNext($(this));
});
// change event for selects :
$('.my-select').change(function(){
showNext($(this));
});
// Method used to show/hide elements :
function showNext(el){
// check if element has a 'data-next' attribute:
if(el.data('next')){
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// show 'Back' button:
$('#backButton').show();
// show the element which id has been stored in 'data-next' attribute:
$(el.data('next')).show();
// Push the parent element ('.hideFirst') into history array:
history.push(el.closest('.hideFirst'));
}
}
// click event for 'back' button:
$('#backButton').click(function(){
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// remove the last '.hideFirst' element from 'history' array and show() it:
history.pop().show();
// hide 'back' button if history array is empty:
history.length || $(this).hide();
}).hide(); // hide 'back' button on init
});
DEMO

adding div around link using jquery

I am adding a div around a link on click of a button. but when i click button multiple times, it adds multiple divs.
<li>
<label> </label>
<div class="deletebutton">
<label> </label>
<div class="deletebutton">
<label> </label>
<div class="deletebutton">
<input type="button" id="ctl00_ContentPlaceHolder1_ctrlAddPhotos_RadUpload1remove1" value="Remove" class="ruButton ruRemove" name="RemoveRow">
</div>
</div>
</li>
How can i make sure that it first checks if there is a div around link and then adds.
I am using following code:
var parentTag = $(".ruRemove").parent().get(0).tagName;
if (parentTag == 'LI') {
$(".ruRemove").wrap("<div class='data deletebutton'></div>");
$(".deletebutton").before("<label></label>");
} else {
var par = $('.deletebutton').parent();
if (par.is('div')) par.remove();
$(".ruRemove").wrap("<div class='data deletebutton'></div>");
var prev = $('.deletebutton').prev();
if (prev.is('label')) prev.remove();
$('.deletebutton').before("<label></label>");
}
it should become this:
<li>
<label> </label>
<div class="deletebutton">
<input type="button" id="ctl00_ContentPlaceHolder1_ctrlAddPhotos_RadUpload1remove1" value="Remove" class="ruButton ruRemove" name="RemoveRow">
</div>
</li>
when i click button. before clicking html is:
<li>
<input type="button" id="ctl00_ContentPlaceHolder1_ctrlAddPhotos_RadUpload1remove1" value="Remove" class="ruButton ruRemove" name="RemoveRow">
</li>
Here is a solution shown in a jsFiddle.
The code story is
HTML
<button id="myButton">My Button</button
JavaScript
$(function() {
$("#myButton").click(function() {
if ($(this).parent().get(0).tagName !== "DIV") {
$(this).wrap("<div class='myDiv'>");
}
});
});
What the code does is register a callback for a button click. When clicked, we ask for the parent of the button that was clicked and ask if the parent node has a tag name of "DIV" meaning it is a <div>. If it is not a div, then we wrap the button in a div and end. On the next call, the detection of the parent being a div will be true and no new div will be added.
Why don't you just use for example a function that does what you want only on the first click?
So only on the first click of that button adds the div, if you click other times the button, it wont do anything. This way you wont add multiple divs.
To do that you could use for example jQuery:
<script type="text/javascript">
$("#firstclick").one("click",function() {
alert("This will be displayed only once.");
});
</script>
You can check even the jQuery API Documentation regarding one:
http://api.jquery.com/one/

jQuery addClass and removeClass in checkboxes

i am new to jQuery, and i am trying to figure out how to create the jQuery function of the checkboxes, what i want to attain is that, when a user clicked on Yes the checkboxes(which will have a display:none) will have a checkmark. But if a user will click on No the checkmark will be removed.
This will be a selection of multiple Yes and multiple No
have a look at the page im working on http://jsfiddle.net/4x2f52ka/
I have started the script for it, but for some reason, when i started to select Yes on the first selection, another yes to the second selection, and if im gonna select No to the 3rd item, the 2 Yes will be removed. It is fine if i will select all yes and all no, but if im gonna select alternate Yes and No, it doesnt allow me to.
this is my code for the html
<div class="row marginBottom">
<div class="col-xs-6">
<label class="alignMid">Have you found a property?</label>
</div>
<div class="col-xs-6">
<span class="opt_yes"><p style="line-height: 38px; font-size:15px;">YES</p></span>
<span class="opt_no"><p style="line-height: 38px; font-size:15px;">NO</p></span>
<input type="checkbox" name="FoundProperty"/>
</div>
</div>
<div class="row marginBottom">
<div class="col-xs-6">
<label class="alignMid">Would you like a free RP Data Property Report?</label>
</div>
<div class="col-xs-6">
<span class="opt_yes"><p style="line-height: 38px; font-size:15px;">YES</p></span>
<span class="opt_no"><p style="line-height: 38px; font-size:15px;">NO</p></span>
<input type="checkbox" name="FreeRPData" />
</div>
</div>
and this is my code for the jQuery
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('.opt_yes').click(function () {
jQuery(this).addClass('selected');
jQuery('.opt_no').removeClass('selected')
if (jQuery(this).hasClass('selected')) {
jQuery(this).parent().find("input[type='checkbox']").prop('checked', true);
}
});
jQuery('.opt_no').click(function () {
jQuery(this).addClass('selected');
jQuery('.opt_yes').removeClass('selected')
if (jQuery(this).hasClass('selected')) {
jQuery(this).parent().find("input[type='checkbox']").prop('checked', false);
}
});
});
</script>
Can anyone help me please?
You're loosing the context of your check boxes. It works for yes, because you use this, but for the no items, you just grab every 'no box' on the document using jQuery('.opt_no'). Because it's so broad, all 'no box' boxes are affected.
You can very easily narrow your selectors with this syntax: jQuery('selector', context).
In this case, I recommend this.parentNode like so :
jQuery('.opt_yes', this.parentNode).removeClass('selected')
See my demo here: http://jsfiddle.net/m5aug81a/
For more info on using contexts for your jQuery objects, see here
You have to remove selected class only from sibling of yes or no. Here's the code:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('.opt_yes').click(function () {
jQuery(this).addClass('selected');
jQuery(this).siblings('.opt_no').removeClass('selected')
if (jQuery(this).hasClass('selected')) {
jQuery(this).parent().find("input[type='checkbox']").prop('checked', true);
}
});
jQuery('.opt_no').click(function () {
jQuery(this).addClass('selected');
jQuery(this).siblings('.opt_yes').removeClass('selected');
if (jQuery(this).hasClass('selected')) {
jQuery(this).parent().find("input[type='checkbox']").prop('checked', false);
}
});
});
</script>

hasClass('disabled') not working after .addClass('disabled')

With selected the hasClass validation works correctly.
<div class="row dis">
<input class="contact button selected" value="Contact Us">
</div>
However if i remove the selected through jquery:
<div class="row dis">
<input class="contact button" value="Contact Us">
</div>
if (!$('.dis > .contact').hasClass('disabled')) {
$("input.contact").click(function() {
alert('---');
$('.contact').addClass('disabled');
});
}
the hasClass still not find the disabled class after $('.contact').addClass('disabled');.
So, i only want the first alert.
Demo:
http://jsfiddle.net/dWGNJ/2/
You could do it like this..
$('input.contact').on('click',function(){
if( !$(this).hasClass('disabled') )
{
alert('---');
$(this).addClass('disabled');
}
});
Basically, when input.contact is clicked, check if it has the class .disabled - if it doesn't then trigger the alert and add the class .disabled - which in turn prevents it from triggering the second time it's clicked
Or you could have a slightly more elegant way of doing it:
$('.dis').on('click','input.contact:not(.disabled)',function(){
alert('---');
$('.contact').addClass('disabled');
});
Same concept.
There's no .disabled element when your JS runs, so, no .contact is binded with click().

input:radio click function isn't triggering in IE / Firefox

I have a form with multiple inputs / radio buttons.
I also have a series of Yes & No radio buttons. When the "Yes" radio button is checked, I have some data slide down beneath.
HTML:
<div class="item seperator first clearfix">
<label>test</label>
<div class="radioWrap">
<label class="yes">
<input class="homepageContent" name="homepageContent" type="radio" value="yes" />
</label>
<label class="no">
<input class="homepageContent" name="homepageContent" type="radio" value="no" checked />
</label>
</div>
</div>
<div class="extrasInner">
<div class="item clearfix">
<label for="theContent">Your Content:</label>
<textarea id="theContent" name="theContent"></textarea>
</div>
</div>
<div class="extrasOuter hide clearfix">
Make Changes
<span>Click "Make Changes" to update.</span>
</div>
The jQuery:
$("input:radio[name=homepageContent], input:radio[name=addSocialIcons], input:radio[name=addTracking]").click(function() {
var value = $(this).val();
if (value == 'yes') {
$(this).parent().parent().parent().next().slideDown();
$(this).parent().parent().parent().next().next().slideDown();
} else {
$(this).parent().parent().parent().next().slideUp();
$(this).parent().parent().parent().next().next().slideUp();
}
});
Question 1) This works absolutely fine in Google Chrome, but not in Firefox and IE. It doesn't seem to recognise the click function?
Solved: I had a function within one of my files that removes the value from input fields on focus and this was stripping the value of the radio buttons as well in IE / Firefox (but not chrome!).
Question 2) Is my DOM traversing for the slideUp / slideDown an acceptable way of achieving what I'm trying to do? Are there any disadvantages to how I'm doing it and can it be improved?
Answer to #1
As Anthony Grist pointed out, there doesn't seem to be an issue with the click function.
Answer to #2
Your DOM traversal seem a bit unnecessary. In fact, your DOM structure is in need of rearrangement.
Using a checkbox instead of radio buttons. A checkbox only accepts two values: true or false, or in your case, yes or no. It seems more suitable.
Encapsulate your extras inner and extras outer divs inside your item div instead of having it next to the checkbox. This way, you make it easier to traverse within the item.
Also, you should read up on the different types of traverse functions JQuery has:
.parent() / .parents()
.children()
.closest()
.next()
.prev()
.siblings()
.find()
and many more.
Knowing all of these traverse functions, you'll most likely never ever do parent().parent().parent()... again. :)
Here's a JSFiddle example | Code
HTML
<ul>
<li class='item'>
<label>
<input class="homepageContent" name="homepageContent" type="checkbox" value="yes" />
Item 1
</label>
<div class='extras'>
<div class='inner'>
<label>
Your Content:<textarea name="content"></textarea>
</label>
</div>
<div class='outer'>
Make Changes
<span>Click "Make Changes" to update.</span>
</div>
</div>
</li>
</ul>
Javascript
$("input:checkbox").click(function() {
var $this = $(this),
$item = $(this).closest(".item");
if($this.is(':checked')){
$(".extras", $item).slideDown();
}else{
$(".extras", $item).slideUp();
}
});
CSS
.extras{
display: none;
}
Value of the radio button will always be same, no matter it is checked or not. If you want to know the particular radio button is checked or not then use this code. Based on the status of the radio button do your stuff.
var value = $(this).attr('checked')
That is working for me in FF (jsfiddle), although the DOM looks a little convoluted (I'm guessing because it's missing a lot of your other CSS/resources).
I think you can simplify the jQuery selectors a lot. Generally, using simple ID or class selectors will make the your page much more performant (and simpler!)
$('.homepageContent').click(function() {
var value = $(this).val();
if (value == 'yes') {
$('.extrasInner').slideDown();
$('.extrasOuter').slideDown();
} else {
$('.extrasInner').slideUp();
$('.extrasOuter').slideUp();
}
});
Hopefully doing something like this makes it work cross browser better too.
try this way
$("input:radio[name=homepageContent], input:radio[name=addSocialIcons], input:radio[name=addTracking]").click(function() {
var value = $(this).val();
if (value == 'yes') {
$(this).parents('.seperator').next().slideDown();
$(this).parents('.seperator').next().next().slideDown();
} else {
$(this).parents('.seperator').next().slideUp();
$(this).parents('.seperator').next().next().slideUp();
}
});
EDIT
​
and also a point
wrap your code inside
$(document).ready(function(){});
like this
$(document).ready(function(){
$("input:radio[name=homepageContent], input:radio[name=addSocialIcons], input:radio[name=addTracking]").click(function() {
var value = $(this).val();
if (value == 'yes') {
$(this).parents('.seperator').next().slideDown();
$(this).parents('.seperator').next().next().slideDown();
} else {
$(this).parents('.seperator').next().slideUp();
$(this).parents('.seperator').next().next().slideUp();
}
});
});

Categories

Resources