I have a lot of input tags for the following form:
<input class="checkbox" type="checkbox" value="something_I_need_when_checked">
I need the value of all the checked boxes. When I call console.log(d3.selectAll("input.checkbox:checked").property("value")) I only see the value of the first element. This post had some leads on how to change these values (EDIT: I don't want to change anything; I just want the values). I tried using the selection.each(function()) idea that was suggested but I didn't get me anywhere. How can I get all values in my selection.
I'm a n00b, be nice. Thanks ~
selection.each does work. However, you have to call it after clicking the checkboxes.
In this demo, the selection will be created after you click the button named "Check". Click the boxes you want, and after that click the button:
d3.select("button").on("click", function() {
var boxes = d3.selectAll("input.checkbox:checked");
boxes.each(function() {
console.log(this.value)
})
});
<script src="https://d3js.org/d3.v4.js"></script>
<input class="checkbox" type="checkbox" value="foo">foo
<input class="checkbox" type="checkbox" value="bar">bar
<input class="checkbox" type="checkbox" value="baz">baz
<input class="checkbox" type="checkbox" value="foobar">foobar
<input class="checkbox" type="checkbox" value="foobaz">foobaz
<button>Check</button>
EDIT: storing the checked values in an array:
var checked = [];
d3.select("button").on("click", function() {
var boxes = d3.selectAll("input.checkbox:checked");
boxes.each(function() {
checked.push(this.value)
});
console.log(checked)
});
<script src="https://d3js.org/d3.v4.js"></script>
<input class="checkbox" type="checkbox" value="foo">foo
<input class="checkbox" type="checkbox" value="bar">bar
<input class="checkbox" type="checkbox" value="baz">baz
<input class="checkbox" type="checkbox" value="foobar">foobar
<input class="checkbox" type="checkbox" value="foobaz">foobaz
<button>Check</button>
Another way to get the fields into an array is to use the map function. In the example below, I build off of Gerardo Furtado's answer.
d3.select("button").on("click", function() {
var checkedBoxes = d3.selectAll("input.checkbox:checked").nodes().map(box => box.value);
console.log(checkedBoxes)
});
<script src="https://d3js.org/d3.v5.js"></script>
<input class="checkbox" type="checkbox" value="foo">foo
<input class="checkbox" type="checkbox" value="bar">bar
<input class="checkbox" type="checkbox" value="baz">baz
<input class="checkbox" type="checkbox" value="foobar">foobar
<input class="checkbox" type="checkbox" value="foobaz">foobaz
<button>Check</button>
Related
<input type="checkbox" class="allCheck" />all
<input type="checkbox" class="checks" />shoes
<input type="checkbox" class="checks" />bag
<input type="checkbox" class="checks" />car
how to unable and uncheck other checkbox if checkbox all is checked?
NOTE: I want to check multiple checkbox EXCEPT ALL if ALL is checked the others must be unchecked and disabled.
It's fairly straight-forward, but there are gotchas:
If .allCheck is changed by the user, drive the .checks checkboxes from it
If a .checks checkbox is changed by the user, drive the .allCheck checkbox based on whether all or none of .checks are (now) checked
// If `.allCheck` is changed by the user, drive the `.checks` checkboxes from it
$(".allCheck").on("change", function() {
$(".checks").prop("checked", this.checked);
});
// If a `.checks` checkbox is changed by the user, drive the `.allCheck`
// checkbox based on whether all or none of `.checks` are (now) checked
$(".checks").on("change", function() {
var all = $(".checks").get().every(function(cb) {
return cb.checked;
});
$(".allCheck").prop("checked", all);
});
<label><input type="checkbox" class="allCheck" />all</label>
<label><input type="checkbox" class="checks" />shoes</label>
<label><input type="checkbox" class="checks" />bag</label>
<label><input type="checkbox" class="checks" />car</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Note in the above I have not done this
...and disabled
We can, but it's not the way these things are usually most useful. Instead, the above makes it easy to pick all but one (by ticking "all," then unticking the one).
But if you really want that disabled behavior, granted it's a bit simpler: You flag disabled via .prop("disabled", flag) and only have to handle changes to .allCheck.
$(".allCheck").on("change", function() {
$(".checks")
.prop("checked", this.checked)
.prop("disabled", this.checked)
});
<label><input type="checkbox" class="allCheck" />all</label>
<label><input type="checkbox" class="checks" />shoes</label>
<label><input type="checkbox" class="checks" />bag</label>
<label><input type="checkbox" class="checks" />car</label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$('.allCheck').click(function(){
$('.checks').prop('checked',$(this).prop('checked'));
$('.checks').prop('disabled',$(this).prop('checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="allCheck" />all
<input type="checkbox" class="checks" />shoes
<input type="checkbox" class="checks" />bag
<input type="checkbox" class="checks" />car
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.
Hello I've got a question about chechbox.
This code checked/unchecked all checkboxes if first one is checked/unchecked.
But I want to do something else with that. I want to add function that, if all of checkboxes are checked then the first one too, but when one or more of the checkboxes are unchecked then first one will be unchecked.
<input class="checkbox" onClick=Show("checkbox") type="checkbox" name="checkboxAll" value="all">
<input class="checkbox" type="checkbox" name="checkboxname1" value="1">
<input class="checkbox" type="checkbox" name="checkboxname2" value="2">
<input class="checkbox" type="checkbox" name="checkboxname3" value="3">
js code:
function Show( a ) {
if ( $("."+a).attr('checked') == true )
$("."+a).attr('checked', true);
else
$("."+a).attr('checked', false);
}
change your child element class names and call it in your show function. It will do the work for you. It is not working right now as expected as the class names are same for 1st one also as the others.
I have changed the names of you checkBoxes a bit, but from what I can understand in your question, this will work:
<input id="first" onClick="Show();" type="checkbox" name="checkboxAll" value="all">
<input class="checkbox" onClick="check();" type="checkbox" name="checkboxname1" value="1">
<input class="checkbox" onClick="check();" type="checkbox" name="checkboxname2" value="2">
<input class="checkbox" onClick="check();" type="checkbox" name="checkboxname3" value="3">
and the js:
function Show() {
if ($('#first').is(':checked')){
$(".checkbox").prop('checked', true);
}
else{
$(".checkbox").prop('checked', false);
}
}
function check(){
allChecked = true;
$(".checkbox").each(function(){
if (!$(this).is(':checked')){
allChecked = false;
}
});
if (allChecked){
$("#first").prop('checked', true);
}
else{
$("#first").prop('checked', false);
}
}
It is better to use the "prop" than the "attr" function, see here: How to check whether a checkbox is checked in jQuery?
Try this
$(function(){
$('input[name="checkboxAll"]').change(function(){
$('input[name^="checkboxname"]').prop("checked",$(this).is(':checked'))
});
$('input[name^="checkboxname"]').change(function(){
var a=$('input[name^="checkboxname"]').length;
if( $('input[name^="checkboxname"]').filter(":checked").length==a){
$('input[name="checkboxAll"]').prop("checked",true)}
else
{
$('input[name="checkboxAll"]').prop("checked",false)
}
});
});
DEMO
Include jQuery and copy and paste this code
Its working.......
<script>
$(function(){
$('#select_all_').click(function(){
if($('#select_all_').is(':checked')){
$(".check_").attr ( "checked" ,"checked" );
}
else
{
$(".check_").removeAttr('checked');
}
});
$('.check_').click(function(){
$.each($('.check_'),function(){
if(!$(this).is(':checked'))
$('#select_all_').attr('checked',false);
});
});
});
</script>
<input type="checkbox" name="chkbox" id="select_all_" value="1" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
<input type="checkbox" name="chkbox" class="check_" value="Apples" />
<input type="checkbox" name="chkbox" class="check_" value="Bananas" />
I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example
I am using the following function that I just found here on SO that does the work with regards to my question only one issue is that, I have a long list of selection and when a user check more than 3-4 checkboxes some of the text or value that is added on the textarea are no longer visible. Is there any way so that everytime a box is check the text that is being added to the text area is always visible? Any help is greatly appreciated.
-thanks ahead!
<input type="text" value="" class="textfield" id="video0_tags" name="video0_tags">
<div class="taglist">
<label><input type="checkbox" value="2D Animation">2D Animation</label>
<label><input type="checkbox" value="3D Animation">3D Animation</label>
<label><input type="checkbox" value="Animatronics">Animatronics</label>
<label><input type="checkbox" value="Architectural">Architectural</label>
<label><input type="checkbox" value="Cartoon">Cartoon</label>
<label><input type="checkbox" value="Cell Animation">Cell Animation</label>
<label><input type="checkbox" value="Character Animation">Character Animation</label><label><input type="checkbox" value="Cut & Paste">Cut & Paste</label>
<label><input type="checkbox" value="Doodle">Doodle</label>
<label><input type="checkbox" value="HDR">HDR</label>
<label><input type="checkbox" value="High Speed">High Speed</label>
<label><input type="checkbox" value="Illustration">Illustration</label>
<label><input type="checkbox" value="Live Action">Live Action</label>
<label><input type="checkbox" value="Macro">Macro</label>
<label><input type="checkbox" value="Motion Design">Motion Design</label>
<label><input type="checkbox" value="Motion Graphics">Motion Graphics</label>
<label><input type="checkbox" value="Moving Installation">Moving Installation</label>
</div>
function updateTextArea() {
var allVals = [];
$('.taglist :checked').each(function() {
allVals.push($(this).val());
});
$('#video0_tags').val(allVals)
}
$(function() {
$('#video0_tags input').click(updateTextArea);
updateTextArea();
});
first, you will need to have a textarea element, so change the input tag with the textarea.
Then on updateTextArea function, you can set the rows attribute on it so that all the text within it is visible. see http://jsfiddle.net/7b5fk/1/
First, you'll want to change video0_tags to a textarea. Next, you'll want to attach the .click() event to each checkbox so that every selection updates the textarea accordingly.
<textarea id="video0_tags"></textarea>
$(document).ready(function(){
$(".taglist input").click(function(){
$("#video0_tags").text('');
$(".taglist :checked").each(function(){
$("#video0_tags").append( $(this).val() + "\n");
});
});
});
Change the text input to a textarea and it will automatically add a scrollbar as it needs it.