Get checkbox state in array with javascript or jquery - javascript

I have on a devexpress grid one column with a checkbox. It is a simple checkbox column, which depends on which checkbox is checked I need to invoke different methods, it is not bind to a property from model.
I need to know which row is selected. I have tried to resolve this with this javascript code:
if (document.getElementById('selectDamage').checked) {
alert("checked");
var checkedValues = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
console.log(checkedValues);
} else {
alert("You didn't check it! Let me check it for you.");
}
This returns only the checked values. I need to return something like Array{on, off, on}, the first is checked, the second one is unchecked and the last is checked. Is there a way in javascript or jquery to do that?

first add checkbox in grid then take a button and set onclick function of this button , then all checked data will go through array and finally split the array value and do your further job.(array value are saved into hidden field, i used hidden field and set the id lblarr )
<dx:GridViewDataColumn >
<HeaderTemplate>
</HeaderTemplate>
<DataItemTemplate>
<input type="checkbox" class="case" id="chkchild" name="checkboxModel" value='<%#Eval("SALE_DOC_#") %>' />
</DataItemTemplate>
</dx:GridViewDataColumn>
<script>
$('#btn1').click(function () {
var CheckCount =$('input:checkbox[name="checkboxModel"]:checked').length;
if (CheckCount > 0)
{
var valuesArray =
$('input:checkbox[name="checkboxModel"]:checked').map(function () {
return this.value;
}).get().join(",");
$('#<%=lblarr.ClientID%>').val(valuesArray);
}
else {
alert('Please check at least one data!')
}
})
</script>

Depending on the layout of your html, you could do something like this to get an updated array of indexed checked states
var els = $("table#gvDamages3_DXMainTable input[type=checkbox]");
els.on("change", function(){
var vals = [];
els.each(function() {
vals.push(this.checked);
});
console.log(vals);
});

Related

How to keep a stored array of input checkbox value?

I have a input checkbox that act as a category filter. I want to store only those values of input checkboxes in an array that are checked in a var checkedAttr. Then do a test if any of the already existing values match any in the array and if it does delete it. The problem I'm having is that... when an input checkbox is clicked, it will store it as many times as the $each loop goes or input checkboxes there are, in this case (three times). I also noticed when unchecking more than one, then rechecking the same one, it will add the values as many times as the $each loop goes and will somehow bypass deleting from the array. I just want to simply add (checked values) / delete (unchecked values) from the array every time the user checks or unchecks.
Here's a jsfiddle.
HTML:
<div id="category-list">
<h1>Categories</h1>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>
jQuery:
var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
if($(this).is(':checked')) // checked
{
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
$('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
{
checkedAttr.push(value); // add value to array
console.log("checkedAttr:", checkedAttr);
}
else // if it does match...
{
checkedAttr.splice(i, 1);// remove it from array
console.log("checkedAttr:", checkedAttr);
}
});
// check which attributes are checked and store in 'checkedAttr' array
//$('input[name=filter]').each(function(i, item){
//});
}
else // unchecked
{
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
Check it Brother its working as you want
var checkedAttr = [];
$('#category-list :checkbox').change(function()
{
checkedAttr = [];
$('#category-list :checkbox').each(function(i, item){
if($(item).is(':checked'))
{
checkedAttr.push($(item).val());
}
});
console.log("checkedAttr:", checkedAttr);
});
You can also check it in JSFiddle
https://jsfiddle.net/xdrLra77/
You can do it simply with a mapcall
var checkedAttr = [];
$('#category-list :checkbox').change(function() {
checkedAttr = $('#category-list :checked').map(function(){
return $(this).val();
}).get();
console.log(checkedAttr);
});
(Updated jFiddle)
(Edit: better yet, put the condition in the jQuery selector)
Edited
var checkedAttr = []; // array for checked attributes
//first load, see what is checked
$('#category-list :checkbox').each(function(){
if($(this).is(':checked')) // checked
checkedAttr.push($(this).val())
})
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
var position = checkedAttr.indexOf($(this).val());
if($(this).is(':checked')) // checked
{
if(position == -1){ // dnot exist in array, add
checkedAttr.push($(this).val());
console.log("checkedAttr:", checkedAttr);
}else{ // exist in array, do nothing
//do nothing
}
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
else // unchecked
{
if(position == -1){ // dont exist in array, do nothing
//do nothing
}else{ // exist in array, remove
checkedAttr.splice(position,1);
console.log("checkedAttr:", checkedAttr);
}
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
You can get the checked elements by using $('.categories:checked'). Then you may iterate through those values to get the actual values
var checkedValues= $('.categories:checked');
var valuesArray=[];
$.each(checkedValues, function(checkedValue){
valuesArray.push(checkedValue.value)
}
Use $.inArray:
if (index === -1 && $(this).is(':checked')) {
checkedAttr.push(value); // add value to array
console.log("added:", checkedAttr);
} else if (index !== -1 && ! $(this).is(':checked')) {
checkedAttr.splice(index, 1);// remove it from array
console.log("removed:", checkedAttr);
}
Amended fiddle: https://jsfiddle.net/o1rmz1o1/4/

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

jQuery get checked checkboxes from name[]

I have checkboxes like so:
<ul id="searchFilter">
<li><input type="checkbox" name="price[]" class="cb_price" value="1"> $200,000 to $299,999</li>
<li><input type="checkbox" name="price[]" class="cb_price" value="3"> $300,000 to $399,999</li>
<li><input type="checkbox" name="price[]" class="cb_price" value="5"> $400,000 to $499,999</li>
<li><input type="checkbox" name="price[]" class="cb_price" value="8"> $500,000+</li>
</ul>
How would I alert the price[] to see what is checked? I am very new at jquery :(
First, you can get the checkboxes by name:
var checkboxes = $('input[name="price[]"]');
Then, to get the values of the checked ones, you can filter by the pseudo selector :checked, and then collect their values:
checkboxes.filter(":checked").map(function () {
return this.value;
}).get()
DEMO: http://jsfiddle.net/Fn9WV/
References:
jQuery().filter() - http://api.jquery.com/filter/
jQuery().map() - http://api.jquery.com/map/
You can try this:-
var selected = [];
$('[name="price[]"]:checked').each(function(checkbox) {
selected.push(checkbox);
});
Use the selector $('#searchFilter [name="price[]"]:checked') with jquery to find all the checked checkboxes with the name "price[]" in this form. This will be zero or more elements, depending on how many are checked.
Then use the jquery each() function to iterate over the found checkbox elements, and collect their values into the "checked" array. In the callback function to each(), the this points to the current element's dom node, wrap it with $(this) to create a jquery object and use .val() to retrieve the value from it.
Finally merge the items into a string, to form a comma separated list using the join() function of the "checked" array. It can be an empty string if none of the checkboxes are checked.
var checked = [];
$('#searchFilter [name="price[]"]:checked').each (function (i, e)
{
checked.push ($(this).val ());
});
alert (checked.join (','));
Notice that other answers used this.value to retrieve the "value" attribute of the checkbox instead of using $(this).val(), which is the jquery way to do it and less error prone.
Try the following:
var alert="";
$('input[type=checkbox]').each(function () {
if($(this).attr("checked") == 1)) alert += $(this).val();
if(alert.length > 1) alert(alert);
});
One way would be to set each checkbox to a specific id. Then you could use $('#' + id).is(":checked") to see if the checkbox is checked. If the checkbox is checked, you could get the range and store it in a variable. You can then return that variable.
Check this page if you need some help with the checkbox.
//get val on click
$(document).on('click', ".cb_price", function () {
if ($(this).is(':checked')) {
alert($(this).val());
}
});
//a button to call the function
$(document).on('click', ".some_button", function () {
function getitems();
});
function getitems(){
$(".cb_price").each(function () {
//
var $chk = $(this);
if ($chk.is(':checked')) {
checkboxes = checkboxes + $(this).val() + ","
}
});
alert(checkboxes);
}

MVC 4 EditorFor bool Checkbox always posting True

I have a bool property in my model. Its value is false when rendering the view. But when I submit the form, the value of TRUE is being passed to the controller. I am using a custom js function to get the values from the form to submit to a controller action. I am not sure how to get the correct value from the checkbox.
My model property:
public bool RushOrderFlag { get; set; }
The view markup:
#Html.EditorFor(model => model.RushOrderFlag)
The HTML Rendered:
<input class="chkbx" data-val="true" data-val-required="The Rush? field is required." id="RushOrderFlag" name="RushOrderFlag" type="checkbox" value="true">
<input name="RushOrderFlag" type="hidden" value="false">
My JS function
function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
Criteria[this.name] = $("#" + this.name).val();
});
return Criteria;
};
Even if in the console I put $('[name="RushOrderFlag"]').val(), after clicking the check box on and off, it is always returning true.
What am I doing wrong?
try
function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
Criteria[this.name] = false;
if ($("#" + this.name).is(':checked'))
Criteria[this.name] = true;
});
return Criteria;
};
Thanks all for the hints...in the end it had to be a bit more complex due to the way the razor creates 2 input controls for the checkbox. So here is what I had to do:
function GetFilterCriteria() {
var Criteria = {};
$('#frmCriteria input').each(function () {
if ($(this).attr('type') != 'hidden') {
if ($(this).attr('type') == 'checkbox') {
Criteria[this.name] = this.checked;
} else {
Criteria[this.name] = $("#" + this.name).val();
}
}
});
return Criteria;
};
I don't like it because if I ever want a hidden input, this will skip that. But for now it works. I find it hard to believe that it has to be this difficult :(
you can try using .CheckBoxFor() you will get an input element only.
for the checked property you can use:
$('#CurrentMailTemplateEnabled').get()[0].checked
to get the value by getting the DOM element first. At least that worked for me.

Auto populate the textbox value with values checked in checkboxes but retain the values that are manually entered

I used the jquery below to auto populate a textbox based on values of checked or unchecked check boxes
function updateTextArea() {
var allVals = [];
$('#all :checked').each(function () {
allVals.push($(this).val());
});
document.getElementById('txtbox').value = allVals;
}
$(function () {
$('#all input').click(updateTextArea);
updateTextArea();
});
and my html code is
<div id="all">
<input id="txtbox" type="text" Height="100px" Width="770px" />
<input id="Checkbox2" type="checkbox" value="abc1#abc.com" />
<input id="Checkbox3" type="checkbox" value="abc2#abc.com" />
<input id="Checkbox4" type="checkbox" value="abc3#abc.com" />
<input id="Checkbox5" type="checkbox" value="abc4#abc.com" />
</div>
The above jquery works wells for every check and uncheck events of checkboxes and populating its values to textbox separated by comma, My issue is if someone manually enters some email separated by comma in the above textbox I want that value to be retained and not to be refreshed for the check and uncheck events of my check box. How can I achieve this?
The general technique that I would use to solve this is:
On every check or uncheck:
1. Split the list by comma into an array.
2. Gather all preset email values that are checked (you're doing this already).
3. Find every split value that isn't in the preset array, and set it aside.
4. Insert all your checked preset values, and then add in all the oddballs, or vice versa.
This doesn't preserve order, but it does retain any manually entered values. Retaining order could be done but would be a little more tricky.
You might also consider just having a separate "additional email" text box which would reduce the complexity of this and potentially make it more intuitive for the user.
Code:
function updateTextArea() {
var allVals = [];
var checkedVals = [];
$('#all input[type=checkbox]').each(function () {
allVals.push($(this).val());
});
$('#all :checked').each(function () {
checkedVals.push($(this).val());
});
var potentialOtherEmails = $("#txtbox").val().split(",");
var confirmedOtherEmails = [];
$(potentialOtherEmails).each(function(index,value) {
if ($.inArray(value, allVals) == -1) {
confirmedOtherEmails.push(value);
}
});
$("#txtbox").val($.merge(checkedVals,confirmedOtherEmails));
}
$(function () {
$('#all input').click(updateTextArea);
updateTextArea();
});
There you go....
$(function () {
txtbox = $("#txtbox");
var prevVal;
$("input[type='checkbox']").click(function() {
prevVal = txtbox.val();
if($(this).is(":checked"))
{
txtbox.val(prevVal + $(this).val() + ", ");
}
else
{
prevVal = prevVal.replace($(this).val()+", ", "");
txtbox.val(prevVal);
}
});
});
One note of caution on your existing code, you're querying the DOM too much (iterating over checkboxes on every check made), don't do that. Also, why you use document.getElementById when you have JQuery available? :-) this may not be a perfect solution, but works!!

Categories

Resources