jQuery get checked checkboxes from name[] - javascript

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);
}

Related

Get checkbox state in array with javascript or jquery

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);
});

jQuery Get data-attribute of all checkbox into a string

I have a list of checkboxes that looks like this:
<input type="checkbox" class="pcb" value="1" data-id="99">
<input type="checkbox" class="pcb" value="2" data-id="98">
<input type="checkbox" class="pcb" value="3" data-id="97">
And originally I only needed the value inside the value attribute of the checked checkbox. I use this javascript/jquery code to do that:
var receiptNos = $("#result input:checkbox:checked").map(function () {
return $(this).val();
}).get();
Using this code gives me: receiptNos = '1,2,3'
Now I need to have another string variable that will hold the content of data-id of all checked checkboxes: receiptNos2 = '99,98,97'
I tried using:
var receiptNos2 = $("#result input:checkbox:checked").attr('data-id').map(function () {
return $(this).val();
}).get();
but it doesn't work. Any ideas?
Instead return $(this).val(); you can use return $(this).data('id');
var receiptNos2 = $("#result input:checkbox:checked").map(function () {
return $(this).data('id')
}).get();

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/

Can't get data attribute value from radio button but can from select option

I've written some code that allows me to determine which select option is to be checked based on what is saved to the mysql db. To be able for that to work I need to print value of a data attribute to a hidden input so that I can store the option selected.
My code is working just fine when it comes to the select options, but doesn't seem to be working with the radio buttons. I've put together a demo of the two in jsfiddle or example which can be found here:
http://jsfiddle.net/5ax5Q/
Here is the code, first the html:
<input data-checked="yes" type="radio" name="product-attr-wifi" value="100" checked />Yes
<input data-checked="no" type="radio" name="product-attr-wifi" value="200" />No
<br>
<input type="text" name="product-attr-wifi-checked" />
Here is the jquery:
var optionChecked = function (checkedInput, checkedOuput) {
$(document).ready(function () {
$(checkedInput).bind("change", function () {
var checkedValue = $(this).find(":checked").attr("data-checked");
$(checkedOuput).val(checkedValue);
});
$(checkedInput).trigger("change");
});
};
optionChecked('input[name="product-attr-wifi"]', 'input[name="product-attr-wifi-checked"]');
In the case of radio button, you don't have to use find() because this refers to the radio element which has the data attribute
var optionChecked = function (checkedInput, checkedOuput) {
$(document).ready(function () {
$(checkedInput).bind("change", function () {
var checkedValue = $(this).attr("data-checked");
$(checkedOuput).val(checkedValue);
});
$(checkedInput).filter(':checked').trigger("change");
});
};
Demo: Fiddle
Try this
var optionChecked = function (checkedInput, checkedOuput) {
$(document).ready(function () {
$(checkedInput).on("change", function () {
var checkedValue = $(this).filter(':checked').attr("data-checked");
$(checkedOuput).val(checkedValue);
});
$(checkedInput).filter(':checked').trigger("change");
});
};
DEMO

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