This question already has answers here:
How to implement "select all" check box in HTML?
(31 answers)
Closed 9 years ago.
I'm trying to have a checkbox called 'All' that when checked, also checks the rest of the checkboxes in my form. I have basically no javascript experience so sorry if this is really basic. I patched this together from looking at posts like this and this.
<script type="text/javascript">
function checkIt(checkbox)
{
document.GetElementById("1").checked = true;
document.GetElementById("2").click();
}
</script>
My HTML looks like this:
<form>
<input type="checkbox" id="A" onclick="checkIt(this)">All<br></input>
<input type="checkbox" id="1">One<br></input>
<input type="checkbox" id="2">Two<br></input>
</form>
How can I get checkboxes 1 and 2 to change when I select checkbox All? Thanks.
Since you are not familiar with javascript, I suggest looking into the jQuery javascript library. Many coders find it simpler to learn/use, and there is no debate that it requires MUCH less typing.
Here are some introductory jQuery tutorials if you are curious.
To solve your problem, I added a class to the checkboxes that you wish to automatically check/uncheck, and used that class to check/uncheck the boxes.
Working jsFiddle here
HTML:
<form>
<input type="checkbox" id="A">All<br></input>
<input type="checkbox" class="cb" id="1">One<br></input>
<input type="checkbox" class="cb" id="2">Two<br></input>
</form>
JQUERY:
$('#A').click(function() {
// alert($(this).prop('checked'));
if ($(this).is(':checked') == true) {
$('.cb').prop('checked', true);
}else{
$('.cb').prop('checked', false);
}
});
Note that this solution uses jQuery, so you need the jQuery library loaded (usually put this line in your head tags):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Related
This question already has answers here:
jquery attr('checked','checked') works only once
(2 answers)
Closed 6 years ago.
I have checkbox code in html below format
<label class="checkbox-inline">
<input type="checkbox" name="category[]" value="1" data-id="1" class="categorychk" checked="checked">Men
</label>
<label class="checkbox-inline">
<input type="checkbox" name="category[]" value="2" data-id="2" class="categorychk" checked="checked">Women
</label>
On ajax success response I doing following jquery code it will work fine.
$.each(data, function(index,value) {
$(".categorychk[data-id="+value+"]").attr("checked",true);
});
But issue is before call I clear all checked marks and then apply above code. But it does not work.
When I add following code after ajax call
$(".categorychk").each(function(){
$(this).removeAttr("checked");
});
Note : If apply above code without clear checked marks then working fine with the previous checked checkbox.
Ok. You're trying to do stuff with attributes, when you should be using properties. Read http://api.jquery.com/attr/, specifically the section entitled "attributes vs properties".
In the meantime, your code will work if you change
$(".categorychk").each(function(){
$(this).removeAttr("checked");
});
to
$(".categorychk").prop("checked", false);
(N.B. you don't need to .each() this, it will operate on all the selected items automatically).
and change
$(".categorychk[data-id="+value+"]").attr("checked",true);
to
$(".categorychk[data-id="+value+"]").prop("checked",true);
Note the use of .prop() instead of .attr()
As documented in how do i check uncheck a checkbox input or radio button you need to use jQuery prop:
$(".categorychk[data-id="+value+"]").prop('checked', true);
And to filter elements by data-id you can use:
$(".categorychk").filter(function() {
return $(this).data('id') == value;
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a form that has the following fields:
<div>
<input name="department" type="radio" value="1" required >
<label for="Orchestra">Orchestra</label>
</div>
<div>
<input name="department" type="radio" value="2">
<label for="Band">Band</label>
</div>
What I would like to be able to do is to display different checkboxes and comment text fields ONLY if the radio button for "Band" is checked. If this is unchecked then, the checkboxes should go away. I found several examples online, but for some reason I can't get them to work. The problem must be that I do not know Javascript or JQuery :( Any help would be appreciated.
I have tried different things that I have seen on stackOverflow and other websites, but I am so clueless about Javascript that I can't get it to work.
I've created a commented fiddle to help you accomplish what you ask, but also clue you in on what's actually going on. I recommend really diving into JavaScript/JQuery with the many resources available online, but for now, I hope my comments will help get you started.
The main takeaway here, is we use JavaScript to "listen" to whether or not the input in question is selected, not selected—based on that value, we can dictate what our view will look like—in this case, hiding or showing element(s).
JS
$(function () {
// Create selectors for relevant DOM elements
var $Department = $('input[name="department"]');
var $BandSelected = $('#BandSelected');
// Create a function that you pass
// the value of the input element in question.
// Return TRUE/FALSE based on equality to 2,
// the `value` associated with the 'Band' input
function isBandsSelected(val) {
return val == 2;
}
// Attach an event listener on `click' of inputs
$Department.click(function () {
// Assign a variable to the function that determines if the input
// we click on is 'Band' (has a value of 2)
var showBand = isBandsSelected($(this).val());
// If `showBand` returns TRUE, show our `BandSelected` div
if (showBand) {
$BandSelected.show();
// If `showBand` returns FALSE, show our `BandSelected` div
} else {
$BandSelected.hide();
}
});
});
Markup
<div>
<input name="department" type="radio" value="1" required>
<label for="Orchestra">Orchestra</label>
</div>
<div>
<input name="department" type="radio" value="2">
<label for="Band">Band</label>
</div>
<div id="BandSelected" class="hidden">
Band is selected
</div>
Demo Fiddle: http://jsfiddle.net/4x1ybqyv/
I'd like to say thanks to the community. You've been a tremendous help so far.
Here's my latest question: I'm designing an online submission form, and one of the questions is a yes/no question with radio buttons. If the lead answers yes, I want a certain question to display. If they answer no, a different question will be displayed instead.
I looked at a few other answers and was able to scrape together some jQuerym but it doesn't seem to be working for me. Here is my javascript and a jsfiddle with the rest of my code.
$(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes') {
$('#ifyes').show();
} else {
$('#ifno').show();
}
});
});
http://jsfiddle.net/yrktj4kz/
Any help would be appreciated!
Looking at the fiddle, you should use
$('.ifyes').show();
and
$('.ifno').show();
instead.
You were using the id's of the input fields to show the element instead of the class of the wrapping div to which the display: hidden; style was applied.
I have updated your code
HTML:
<li>
<label for="coverage">K. Do you have current coverage?</label>
<input type="radio" name="choice" class="radio-toggle" data-target=".ifyes" data-target-group=".ifdiv" /> Yes
<input type="radio" name="choice" class="radio-toggle" data-target=".ifno" data-target-group=".ifdiv" /> No
</li>
<li>
<div class="ifyes ifdiv">
<label for="ifyes">When does the policy expire?</label>
<input type="text" id="ifyes" name="ifyes" value="" />
</div>
<div class="ifno ifdiv">
<label for="ifno">When do you need the policy to take effect?</label>
<input type="text" id="ifno" name="ifno" value="" />
</div>
</li>
and JS:
$(document).ready(function(){
$('.radio-toggle').click(function() {
$($(this).data('targetGroup')).hide();
$($(this).data('target')).show();
});
});
Obviously you need to call the jQuery library.
This is the complete and updated fiddle: http://jsfiddle.net/yrktj4kz/1/
Note that i'm using html data attribute to optimize the js code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have many city input checkboxes. I have given the first checkbox the name All; if the user selects that then only All checkbox gets selected, and not the other city checkboxes.
If the user checks any other city, then the All checkbox should automatically be unchecked. I want to do this with JavaScript or jQuery.
<input type="checkbox" name="city_pref[]" id="city_all" value="0" checked /><label for="city_all">All</label>
<input type="checkbox" name="city_pref[]" id="city_pref_1" value="Chicago" /><label for="city_pref_1">Chicago</label>
<input type="checkbox" name="city_pref[]" id="city_pref_2" value="Texas" /><label for="city_pref_2">Texas</label>
and so on....
Try this
$(function(){
var el=$('input:checkbox[name="city_pref[]"]');
el.on('change', function(e){
if($(this).is(':checked')) el.not($(this)).prop('checked', false);
});
});
DEMO.
Update: (after the clarification of question)
$(function(){
var el=$('input:checkbox[name="city_pref[]"]');
el.on('change', function(e){
if($(this).attr('id')!='city_all')
{
if($(this).is(':checked')) $('#city_all').prop('checked', false);
}
else
{
if($(this).is(':checked')) el.not($(this)).prop('checked', false);
}
});
});
DEMO.
Update:(23-07-2012)
I want the functionality, when no checkbox is selected, then All will get selected automatically
Updated Demo.
You can do it like this,
Live Demo
$('#city_all').change(function(){
if($(this).is(':checked'))
$('input:checkbox[name^=city_pref]').attr('checked','checked');
else
$('input:checkbox[name^=city_pref]').removeAttr('checked');
});
$('input:checkbox[name^=city_pref]').change(function(){
if($('input:checkbox[name^=city_pref]').not(':checked').length > 0)
$('#city_all').removeAttr('checked');
else
$('#city_all').attr('checked','checked');
});
Note: To separate the other and all from the cities give them different name.
Darin's right - although it would be a good idea for someone to give you some tips on how to solve this problem. If I read the question correctly, the only dynamic behaviour you want is when someone ticks a box which is not "All"; in this case, you want the "All" box unticked.
OK, so you need to break the problem down into pieces. Here's what I'd do:
Attach a function to all controls that are not "All". I'd do this with a class selector, but equally you could do the "not name" approach (as per Yograj Gupta's answer)
Inside the event handler, have an if statement that only runs if the control is found to be ticked (i.e. if "All" is selected and you untick a city, nothing happens).
If the if statement runs, untick the "All" control
Each of those items are now small enough that the jQuery docs can be consulted. In this case of course you have some ready-made solutions, but the approach of breaking problems down is very important if you want to self-improve as a programmer.
Addendum: also - and a good tip for forum questions generally - if you find an answer gets you 80% of the way to your requirements, try to implement the other 20% yourself. I agree it's not always possible, since everyone has to ask for help sometimes, but it's good practice that in the long run you'll find helps the learning process.
Even though you should try to implement your own code first before asking for help, I think is fair to help someone who doesn't really know how to start doing something. So, I made this JSFiddle
<input type="checkbox" class="all">all</input>
<input type="checkbox" name="city" class="london city">london</input>
<input type="checkbox" name="city" class="rome city">rome</input>
<input type="checkbox" name="city" class="tokio city">tokio</input>
$('.all').click(function(){
$('input[name=city]').attr("checked", true)
})
$('.city').click(function(){
$('input[type=checkbox]').attr("checked", false)
$(this).attr("checked", true)
})
try this
$('input:checkbox[name^=city_pref]').click(function(){
if(this.id =="city_all"){
$(this).siblings("input:checkbox").attr('checked',false);
}
else{
$('#city_all').attr('checked',false);
}
});
I'll throw mine in here
$(function () {
$('.checkbox-all .all').attr('disabled', true); //comment out if you want them to be able to toggle the all checkbox, but their input would be overwritten so I just disable it.
$('.checkbox-all input[type="checkbox"]').change (function () {
var numSelected = $(this).parent().children(':checked:not(.all)').length;
$(this).siblings('.all').attr('checked', (numSelected == 0));
});
});
With the HTML:
<div class="checkbox-all">
<input class="all" type="checkbox" name="city_pref[]" id="city_all" value="0" checked /> <label for="city_all">All</label><br/>
<input type="checkbox" name="city_pref[]" id="city_pref_1" value="Chicago" /> <label for="city_pref_1">Chicago</label><br/>
<input type="checkbox" name="city_pref[]" id="city_pref_2" value="Texas" /> <label for="city_pref_2">Texas</label>
</div>
FYI, your label elements are set incorrectly in your example, I've set the for attributes correctly in my HTML.
This is my html Code:
<input type="checkbox" name="test" id="test" />
Here i want to check if the checkbox test is checked or not when clicking on that checkbox.
That means there have function to call when clicked the checkbox and in that function check the test is checked or not using javacsript.
How can i do this?
<input type="checkbox" name="test" id="test" onClick="check(this)" />
In your script : function check(element) {
alert(element.checked);
} Hope this may help you, if not let me know.
The answers of this question kind of make me feel down. I thought that one thing jQuery learned to everybody was at least to not use inline event handlers for the sake of unobtrusive javascript.
With unobtrusive javascript, cross-browser, here is a way to do it:
document.getElementById('test').onclick = function() {
alert(this.checked)
}