jQuery Get data-attribute of all checkbox into a string - javascript

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

Related

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

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

Jquery only registers one id

I have three checkboxes that looks like this:
<input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
now i wanted to create some ajax (which is working fine) however only the first checkbox has the event:
here is my Jquery function:
$('#image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
So my question is. why is this click function only happening for one of my checkboxes? (if it matters it is only the first checkbox that is working)
ids must be unique on an html page. Instead use a class in the markup and a class selector in jQuery.
HTML
<input class="image_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
Javascript
$('.image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
IDs have to be unique change the id to class instead
id="image_tagging"
to
class="image_tagging"
then
$('.image_tagging').click(function(){
in html
<input class="image_tagging" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
in js
$('.image_tagging').click(function(){
// your code
});
id must be unique, use class instead or try this...
$('input[type="checkbox"]').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
no need to change any HTML code you wrote already...
ID should be unique in your DOM structure. Use class instead of ID for such things.
<input id="image_tagging" class="img_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
And then instead of #image_tagging use .image_tagging for binding click event
$('.image_tagging').click(function(){

get value of checked checkbox list in array in jQuery

I have list of checkboxes that has all checkbox pre-checked when page load.
Firstly, I want to read all checkboxes (checked) value and store in global array.
Later, whenever any checkbox is clicked by user (un-checked / checked), I want to update the array with values of only checked checkboxes.
All this i want to do in jQuery.
thanks
<input type="checkbox" value="somevalue1" class="chk">
<input type="checkbox" value="somevalue2" class="chk">
<input type="checkbox" value="somevalue3" class="chk">
<input type="checkbox" value="somevalue4" class="chk">
<input type="checkbox" value="somevalue5" class="chk">
<script>
var someGlobalArray = new Array;
$(".chk").click(function() {
someGlobalArray=[];
$('.chk:checked').each(function() {
someGlobalArray.push($(this).val());
});
console.log(someGlobalArray);
});
</script>
Did you mean something like this?
var arrCheckboxes;
var checkboxSelector = "input[type='checkbox']";
$("body").delegate(checkboxSelector , "click", function(){
arrCheckboxes = $(checkboxSelector).map(function() {
return this.checked;
}).get();
});
(Maybe you should change the $("body") to a more precise container)
If you want an array with objects with name (...or id or maybe the element)... you can do something like this:
var arrCheckboxes;
var checkboxSelector = "input[type='checkbox']";
$("body").delegate(checkboxSelector , "change", function(){
arrCheckboxes = $(checkboxSelector).map(function() {
return { name: this.name, val: this.checked };
}).get();
});
I assume that you want is the name or id of the checked items, since checkbox values are boolean?
var checked = {};
$(':input[type="checkbox"]').each(function() {
var name= this.name;
var val = this.checked;
if (val) {
checked[name] = val;
}
}).on('change', function() {
var name = this.name;
var val = this.checked;
if (val) {
checked[name] = val;
} else {
delete checked[name];
}
});
The object checked will then contain keys, and only those corresponding to checked items will appear in that object.
Working demo at http://jsfiddle.net/tFYPF/

Select all radio buttons which are checked with prototype

I have several input elements which look like this:
<input type="radio" checked="checked" value="1" name="handle[123]" />
<input type="radio" checked="checked" value="2" name="handle[456]" />
The number inside the name attribute is an object id i need. Now what I want to do is:
Fetch all input which are of type="radio" and are checked with prototype
Put all ids and values in an associative array
...so the resulting array looks something like this:
array{ 1 => 123, 2 => 456 }
Any ideas?
Here's what I came up with:
var results = [];
document.body.select('input[type=radio]:checked').each(function (element) {
var object = {};
object[element.value] = element.name.match(/\d+/)[0];
results.push(object);
});
new Ajax.Request('/some_url', {
method: 'post',
parameters: results
});
Demo
To get the checked radio button given a form id, and the name of the radio group:
function RF(el, radioGroup) {
if($(el).type && $(el).type.toLowerCase() == 'radio') {
var radioGroup = $(el).name;
var el = $(el).form;
} else if ($(el).tagName.toLowerCase() != 'form') {
return false;
}
var checked = $(el).getInputs('radio', radioGroup).find(
function(re) {return re.checked;}
);
return (checked) ? $F(checked) : null;
}
var value = RF('form_id', 'radio_grp_name');
Hope it helps
$$('input:checked[type=radio]').each(function (ele) {
output[ele.name.match(/\d+/)[0]] = ele.value;
});
This would give the desired output using prototype

Categories

Resources