Showing, hiding checkboxes with jquery using fadeIn fadeOut - javascript

I am writing a form, it has checkboxes, and I wrote a script to show and hide them (specifically hide all other checkboxes when one of them is selected).
I reached this far when I need this to hide the input checkboxes, but what this code below is doing, is: it shows only 1 of checkboxes (the second one). Why, how can I hide both of the checkboxes at the same time ?
$('input:checkbox.individual' && 'input:checkbox.organization').stop(true,true).fadeIn("normal")
this is my html:
<div class="field check check-entity">
<label for="entity_type">For what kind of entity are you requesting sponsorship?<span class="form_required">*</span></label><br><br>
<input type="checkbox" name="entity_type" value="entity_project" class="project"/><label for="entity_project" class="lalbe_project">Project</label>
<input type="checkbox" name="entity_type" value="entity_individual" class="individual"/><label for="entity_individual"class="label_individual">Individual</label>
<input type="checkbox" name="entity_type" value="entity_organization" class="organization"/><label for="entity_organization" class="label_organization">Organisation</label>
</div>

Use a , in the selection string to select multiple groups of elements
$('input.individual:checkbox, input.organization:checkbox')
// ^ see here

Is this the effect you wanted to achieve?
http://jsfiddle.net/z37br/
HTML:
<div class="field check check-entity">
<label for="entity_type">For what kind of entity are you requesting sponsorship?
<span class="form_required">*</span>
</label>
<br><br>
<input type="checkbox" name="entity_type" value="entity_project" data-type="project"/>
<label for="entity_project" class="lalbe_project">Project</label>
<input type="checkbox" name="entity_type" value="entity_individual" data-type="individual"/>
<label for="entity_individual"class="label_individual">Individual</label>
<input type="checkbox" name="entity_type" value="entity_organization" data-type="organization"/>
<label for="entity_organization" class="label_organization">Organisation</label>
</div>
JS:
$('input').change(function() {
if ($(this).prop('checked')) {
var clickedCheckboxType = $(this).attr('data-type');
$('input').each(function() {
if (clickedCheckboxType != $(this).attr('data-type')) {
$(this).fadeOut('fast');
$(this).next().fadeOut('fast');
}
});
}
else {
$('input').fadeIn('fast');
$('input').next().fadeIn('fast');
}
});

Related

How to dynamically get values from multiple check-boxes (jquery) and copy it to textarea?

I have an checkbox "Cut image" which will on select expand four more check-boxes (up, left, right, down) where you can select where image will be cut.
By default, these expanded check-boxes are selected.
What I want to achieve is:
If "cut image" checkbox is selected (and by default all other expanded check-boxes) append text value "Cut image: up, left, right, down" to textarea
If one of the expanded check-boxes are not selected (lets say "up"), remove it's value from appended text in textarea, and show only selected ones, "Cut image: left, right, down"
Html
<input type="checkbox" id="cut-image">
<label for="">Cut image</label>
<div id="main-group">
<input type="checkbox" class="cut-image-up" checked>
<label for="">up</label>
<input type="checkbox" class="cut-image-left" checked>
<label for="">left</label>
<input type="checkbox" class="cut-image-right" checked>
<label for="">right</label>
<input type="checkbox" class="cut-image-down" checked>
<label for="">down</label>
</div>
<textarea name="" id="checkbox-values" cols="20" rows="10"></textarea>
Javascript
$(function(){
$('#cut-image').on('change', function(){
$('#main-group').toggle();
if($(this).is(':checked')){
$('#checkbox-values').val('Cut image (up, left, right, down)');
}else{
$('#checkbox-values').val('');
}
});
})
Here is an jsfiddle also.
I would appreciate any suggestions on how to achieve this behavior.
Thanks.
There are always about a billion ways to do things like this. It seems to me like you need a couple of things:
A way to associate each checkbox with its direction
Something that listens for changes in the checkboxes -- as they are checked and unchecked
Every time a checkbox is changed, we grab all the checked checkboxes, and reattach the directions to the textbox
Here's an updated version. Note the slightly different HTML...
$(function() {
$('#cut-image').on('change', function() {
$('#main-group').toggle();
if ($(this).is(':checked')) {
setCheckboxValues();
} else {
$('#checkbox-values').val('');
}
$('.cut-image').on('change', function() {
setCheckboxValues()
})
});
})
function setCheckboxValues() {
const allCheckedText = $('input.cut-image:checked').map(function() {
return this.value;
}).get()
$('#checkbox-values').val(`Cut image (${allCheckedText.join(', ')})`);
}
#cut-image,
#main-group,
#checkbox-values {
display: block;
margin: 10px 0;
}
#main-group {
display: none;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cut-image">
<label for="">Cut image</label>
<div id="main-group">
<input type="checkbox" class="cut-image" checked value="up">
<label for="">up</label>
<input type="checkbox" class="cut-image" checked value="left">
<label for="">left</label>
<input type="checkbox" class="cut-image" checked value="right">
<label for="">right</label>
<input type="checkbox" class="cut-image" checked value="down">
<label for="">down</label>
</div>
<textarea name="" id="checkbox-values" cols="20" rows="10"></textarea>
This won't completely take care of all the various scenarios but will give you a good start point
Add values to the checkboxes and build array of those values using jQuery map(). Then join() those array values to add to the text
<input type="checkbox" class="cut-image-up" value="up" checked>
JS
$('#cut-image').on('change', function() {
$('#main-group').toggle();
if ($(this).is(':checked')) {
// array of checked checkbox values
var directions = $('#main-group :checkbox:checked').map(function() {
return this.value
}).get().join(', ');
$('#checkbox-values').val('Cut image (' + directions + ')');
} else {
$('#checkbox-values').val('');
}
});
DEMO

Validating if atleast one checkbox is checked or one input field is filled

I need better validation logic, where some Checkboxes and some input fields are grouped together.
The user either have to check at least one checkbox or have to fill at least one input box.
If a checkbox is checked or an input field is filled then the complete group is validated.
What will be the best possible way to validate such a situation?
e.g
<input class="checkbox" type="checkbox" name="check-deal" value="1" grouped="deal" >
<input class="checkbox" type="checkbox" name="check-deal" value="2" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="3" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="4" grouped="deal">
<input class="input-group" type="text" name="deal-name1" value="" grouped="deal">
<input class="input-group" type="text" name="deal-name2" value="" grouped="deal">
I have defined an extra attribute grouped for all input and checkboxes that should be grouped togather
but getting no idea how to validate the group as best practice.
DEMO
Point No.1 : There isn't any attribute called grouped for html as of my knowledge but I would suggest you to use data-* prefixed attribute names like data-grouped or data-anyname which is valid
Point No.2 : I rather categorized your checkboxes and textboxes into separate divs and below is how it is:
<div class="chkbox">
<input class="checkbox" type="checkbox" name="check-deal" value="1" />
<input class="checkbox" type="checkbox" name="check-deal" value="2" />
<input class="checkbox" type="checkbox" name="check-deal" value="3" />
<input class="checkbox" type="checkbox" name="check-deal" value="4" />
</div>
<div class="txtbxs">
<input class="input-group" type="text" name="deal-name1" value="" />
<input class="input-group" type="text" name="deal-name2" value="" />
</div>
<button class="btnValidate">Validate</button>
Point No.3 : Below is how you can validate using jquery
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length; //get checkbox checked length
var filledText=$(".txtbxs .input-group").val()!="";
//get bool value whether any of the text box is filled or not
if(chkLength || filledText) //check with or condition
alert('valid')
else
alert('invalid');
});
UPDATE
DEMO
As #AkshatG pointed in his answer the discrepancy was there in my answer so I've edited it and here is the updated solution.
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length;
var filledText=false; //First set it to false
$.each($(".txtbxs .input-group"),function(index,value){
if($(value).val()!="")
{
filledText=true//if it finds any value then set it to true
return;//break from $.each
}
})
if(chkLength || filledText)
alert('valid')
else
alert('invalid');
});
You first need to take count of each validations. And then check if any of the two has count greater than 0 or not. Guruprasad's answer won't work if you enter text on second textbox because it won't filter all the textboxes. You have to use filter function for this :
$("input[type='text'],textarea").filter(function() {
return $(this).val() != "";
}).length;
Here's a jsfiddle :
http://jsfiddle.net/myfLgpdv/
Hope this helps.

How to toggle div visibility using radio buttons?

I'm working on a project in which I have to toggle the visibility of a <div>.
I've got the following code:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
I would like to togle the business-fields div. So, if none of the radio buttons, or the 'personal' radio button is selected: The div should be hidden. If the 'business' radio button is selected, I want it to show.
Currently, I am using this code:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
However, I was wondering if I can do this using the .toggle() function.
I usually tend not to use JS if possible, therefore here comes a HTML+CSS way approach.
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
The ~ stands for any siblings, that are after the element we defined before the ~ sign.
I'd suggest using the change event, and supplying a Boolean switch to the toggle() method, which will show the jQuery collection of elements if the switch evaluates to true, and hide them if it evaluates to false:
// select the relevant <input> elements, and using on() to bind a change event-handler:
$('input[name="type"]').on('change', function() {
// this, in the anonymous function, refers to the changed-<input>:
// select the element(s) you want to show/hide:
$('.business-fields')
// pass a Boolean to the method, if the numeric-value of the changed-<input>
// is exactly equal to 2 and that <input> is checked, the .business-fields
// will be shown:
.toggle(+this.value === 2 && this.checked);
// trigger the change event, to show/hide the .business-fields element(s) on
// page-load:
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="1">Personal</label>
<label>
<input type="radio" name="type" value="2">Business</label>
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Incidentally, note I've also wrapped the associated text, to indicate the radio-button's purpose, inside of a <label> element to directly associate that text with the <input>, so clicking the text checks the <input> automatically.
References:
change().
on().
toggle().
JS Fiddle
Try this one
<input type="radio" name="type" value="1" checked ="true"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
.business-fields{
display: none;
}
$("input[name='type']").change(function() {
$(".business-fields").toggle();
});
You may use like this:
$("input[name='type']").change(function() {
var status = $(this).val();
if (status != 2) {
$(".business-fields").hide();
} else {
$(".business-fields").show();
}
});
.show and .hide are pretty slow.
https://twitter.com/paul_irish/status/564443848613847040
It's better to toggle a css class on and off with javascript. Set the css of the class to {visibility: hidden} or {display: none}
use the below code
<script>
$(function(){
$(":radio[value=1]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==true)
$('.business-fields').toggle();
});
$(":radio[value=2]").click(function(){
var isVisible = $( ".business-fields" ).is( ":visible" );
if(isVisible==false)
$('.business-fields').toggle();
});
});
</script>
AND HTML is-
<input name="type" type="radio" value="1" >Personal
<input type="radio" name="type" value="2" checked="checked"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
Possibly a more elegant solution, It's a bit more readable in my opinion, and and as #Ollie_W points out it might be more performant that toggle (show/hide).
$('input[name="type"]').on('change', function(event) {
var radioButton = $(event.currentTarget),
isBusiness = radioButton.val() === 'business' && radioButton.prop('checked');
$('.business-fields').toggleClass('hidden', !isBusiness);
}).change();
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="radio" name="type" value="personal">Personal</label>
<label>
<input type="radio" name="type" value="business">Business</label>
<div class="business-fields hidden">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>

Input field appear after selecting a check box. HTML

I have a Twitter Bootstrap form that has 6 vertical check boxes. I need to have an input form field each time they select a checkbox. It could be in the form of a popup or maybe something that appears out to the right of the checkbox. I figure this is some kind of javascript function but I have no idea how to do so. Any suggestions would be greatly appreciated. Each textbox if selected should have a field that pops up asking them for how many years experience they have in this certain field. This will info will be collected via $_POST variables. So each checkbox popup should have its own unique name so i can post it.
<div class="form-group">
<label class="col-md-4 control-label" for="positionsought">Position Sought</label>
<div class="col-md-4">
<div class="checkbox">
<label for="positionsought-0">
<input type="checkbox" name="positionsought" id="positionsought-0" value="Cutting">
Cutting
</label>
</div>
<div class="checkbox">
<label for="positionsought-1">
<input type="checkbox" name="positionsought" id="positionsought-1" value="Sewing">
Sewing
</label>
</div>
<div class="checkbox">
<label for="positionsought-2">
<input type="checkbox" name="positionsought" id="positionsought-2" value="Upholstery">
Upholstery
</label>
</div>
<div class="checkbox">
<label for="positionsought-3">
<input type="checkbox" name="positionsought" id="positionsought-3" value="Frame Department">
Frame Department
</label>
</div>
<div class="checkbox">
<label for="positionsought-4">
<input type="checkbox" name="positionsought" id="positionsought-4" value="Mill Room">
Mill Room
</label>
</div>
<div class="checkbox">
<label for="positionsought-5">
<input type="checkbox" name="positionsought" id="positionsought-5" value="Cushion">
Cushion
</label>
</div>
<div class="checkbox">
<label for="positionsought-6">
<input type="checkbox" name="positionsought" id="positionsought-6" value="Any">
Any
</label>
</div>
</div>
</div>
Although you already have found an answer, I believe that this would work better for your situation since you say you will have 6 checkboxes. This dynamically creates input fields for each checkbox by their names and removes them when the checkbox is unchecked.
First add this function to each checkbox onclick="dynInput(this);"
<input type="checkbox" name="check1" onclick="dynInput(this);" />
and add this to wherever you would like the inputs to display.
<p id="insertinputs"></p>
Then simply add this javascript function to your head.
<script type="text/javascript">
function dynInput(cbox) {
if (cbox.checked) {
var input = document.createElement("input");
input.type = "text";
var div = document.createElement("div");
div.id = cbox.name;
div.innerHTML = "Text to display for " + cbox.name;
div.appendChild(input);
document.getElementById("insertinputs").appendChild(div);
} else {
document.getElementById(cbox.name).remove();
}
}
</script>
JsFiddle here: http://jsfiddle.net/brL6gy7r/
You can use JavaScript here to do the job. When the checkbox is clicked and checked (because you can also check out.) a dialog will pop-up with all input-fields you want. You can change the dialog part to your desires. but this part is your main function:
$(document).ready(function () {
$('#chkBox').click(function () {
if ($(this).is(':checked')) {
// create input field
} else {
// if checkbox is not checked.. dont show input field
}
});
});
For a full demo on how to do this with a dialog, click this link and observe
http://jsfiddle.net/Runman44/5vy1m233/
Notice that you will need jQuery (and jQuery UI if you want to use the dialog like me)
There is a zero-JavaScript version that is dead simple and works in all major browsers. It takes advantage of the :checked pseudo-class and the adjacency selector. It works with an arbitrary number of checkboxes.
HTML:
<input type="checkbox" />
<input type="text" />
CSS:
input[type=text] {
visibility:hidden;
}
input[type=checkbox]:checked + input[type=text] {
visibility:visible;
}
here is the live demo
If you prefer, you can use display:none and display:inline rather than the visibility property.
The example I've provided assumes that the text field immediately follows the checkbox in the markup, but some variant of sibling/child selectors can be used to select it no matter where it is, as long as it is either a sibling or child (direct or indirect) of the checkbox.

bootstrap check/uncheck multiple elements with js

I am trying to make this work but can't make it happen. I have a bootstrap template and i want to check and uncheck multiple checkboxes (like this: http://jsfiddle.net/v6wmV/177/ )
I know this is a common subject with many solutions, but none seem to work for this case and i would like to know why.
This is the code snippet from the view:
<div class="hide" id="states">
<div class="control-group">
<label class="control-label">Select</label>
<div class="check">
<div class="controls">
<label class="checkbox line">
<input type="checkbox" class="all" value="Todas" id="allstates" name="st[25]"/>All
</label>
<label class="checkbox line">
<input type="checkbox" value="Caba" id="" name="st[1]"/>Ciudad Autónoma de Buenos Aires
</label>
<label class="checkbox line">
<input type="checkbox" value="Buenos Aires" id="" name="st[2]"/> Buenos Aires
</label>
<label class="checkbox line">
<input type="checkbox" value="Catamarca" id="" name="st[3]"/> Catamarca
</label>
<label class="checkbox line">
<input type="checkbox" value="Chaco" id="" name="st[4]"/> Chaco
</label>
</div>
</div>
</div>
</div>
and this is my js file (with other functions):
$('.hide').hide();
$('#registered').click(function(){
$('#content').toggle('fast');
});
$('#age').click(function () {
$('#content2').hide('fast');
$('#content1').show('fast');
});
$('#range').click(function () {
$('#content1').hide('fast');
$('#content2').show('fast');
});
$('#with').click(function(){
$('#child').toggle('fast');
});
$('#showstates').click(function(){
$('#states').show('fast');
});
$('#hidestates').click(function(){
$('#states').hide('fast');
});
//function for check/uncheck
$('.all').click(function() {
var $checkboxes = $(this).parent().find('input[type=checkbox]');
$checkboxes.prop('checked', $(this).is(':checked'));
});
this is the fiddle: http://jsfiddle.net/jimena/j56Dy/
which is not working
you need to go up two stages instead of one. parent() gives you the label element, you need to go up to the "controls"-classed div to apply your find method :
var $checkboxes = $(this).parent().parent().find('input[type=checkbox]');
Of course that was to apply minimal change to your code way. The one provided by Joe up here is probably smarter : getting all the checkboxes you want without having to use parent() method. But to do so you might want to id your checkbox group so that you do not select all the checkboxes accross your DOM.
By the way, don't you have to show your hide div at some point to see your checkboxes ?
Edit> OK actually Manish is right with parents it is just right, forget my answer :D

Categories

Resources