Select values of checkbox group with jQuery - javascript

I'm using Zend_Form to output a set group of checkboxes:
<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>
With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:
$("input[#name='user_group[]']").val()
but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?

You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):
$("input[name='user_group[]']:checked")
With those checked items, you can either create a collection of those values or do something to the collection:
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});

I'm not sure about the "#" used in the selector. At least with the latest jQuery, I had to remove the # to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
Now both, items and about work.

Use .map() (adapted from the example at http://api.jquery.com/map/):
var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
return $(domElement).val();
});

With map in instead of each it is possible to avoid the array creation step:
var checkedCheckboxesValues =
$('input:checkbox[name="groupName"]:checked')
.map(function() {
return $(this).val();
}).get();
From the map() page of the docs:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values
get() turns those values into an array.

mhata dzenyu mese. its actually
var selectedGroups = new Array();
$(".user_group[checked]").each(function() {
selectedGroups.push($(this).val());
});

I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[#name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!

I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:
("input[#name='user_group[]']").each( function() {
alert($(this).val());
});
Of course a better selector is available:
$(':checkbox')

var values = $("input[name='user_group']:checked").map(function(){
return $(this).val();
}).get();
This will give you all the values of the checked boxed in an array.

You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}

$(document).ready(function(){
$('#btnskillgroup').click(function(){
getCheckedGroups('skills');
});
$('#btncitiesgroup').click(function(){
getCheckedGroups('cities');
});
var getCheckedGroups = function(groupname){
var result = $('input[name="'+groupname+'"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#div'+groupname).html(resultstring);
}else{
$('#div'+groupname).html(" No checkbox is Checked");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Skills:<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<br>
<input type="checkbox" name="cities" value="Pune"> Pune
<input type="checkbox" name="cities" value="Baramati"> Baramati
<input type="checkbox" name="cities" value="London"> London
<input type="submit" id="btnskillgroup" value="Get Checked Skill group">
<input type="submit" id="btncitiesgroup" value="Get cities checked group">
<div id="divskills"></div>
<div id="divcities"></div>

Related

Javascript foreach calculation [duplicate]

This simple code checks if there is at lease one check box marked,
When I try to get check box array with Firefox I don't- I just the first one,
Same code working fine in IE,
Do I need to make different ID's for the check box elements and iterate them?
Thanks for your help.
<html>
<head>
<script type="text/javascript">
function testCheckBox(){
var vehicle = document.getElementById('vehicle');
for (var i=0; i < vehicle.length; i++){
alert(vehicle[i].checked);
if (trucks[i].checked){
alert('at least one was selected');
return true;
}
}
alert('Please select one');
return false;
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
<br />
<input type="button" name="test" value="test" onclick="testCheckBox();" />
</body>
</html>
getElementById() never returns an array. It only returns a single element (because ids must be unique - i.e. having more than one element with the same id is invalid HTML.) getElementsByTagName() is what you want here:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
if (el.type == 'checkbox' && el.checked) {
alert(el.value + ' is checked');
}
}
(Note: newer browsers support getElementsByClassName, which could also be used.
The problem is that you don't have any element with that id in your HTML. That's a semantic issue. And as you are using checkboxes, I don't think that getElementById is the way to go. You should either use the class attribute or add a containing element for those checkboxes and then iterate over its children elements (the checkboxes).
I wouldn't count on browsers allowing the name attribute as a substitute for IDs. If you assign all of your checkboxes a unique ID, you could just use some conditional checks to see if any of them are checked individually, such as:
function testCheckBox() {
var bikeCB = document.getElementById('bikeCB');
var carCB = document.getElementById('carCB');
if(bikeCB.checked) {
alert('An item is checked');
}else if(carCB.checked) {
alert('An item is checked');
}else { //after all have been checked
alert('No items are checked');
}
}
While you would need to add an ID for each checkbox in the HTML:
<input type="checkbox" id="bikeCB" value="Bike" /> I have a bike<br />
<input type="checkbox" id="carCB" value="Car" /> I have a car
If you are intent on looping through the checkboxes, you could give your form an ID and use the form.elements[] collection to loop through them and test for one being checked:
function testCheckBox() {
var form = document.getElementById('form1'); //get reference to form
var length = form.elements.length; //get length of form.elements array
for(i=0; i<length; i++) { //loop through while i is less than array length
if(form.elements[i].checked) {
alert('An item was checked');
}
}
}
This will alert for every checkbox that is checked. If you just wanted to know once if any were checked, you could possibly set a variable to true if any were checked, and then check if the variable was true after the for loop to know whether to alert or not.
By the way, you appear to be missing a closing </form> tag in your html after the <input> elements.
What you need is getElementsByName, not getElementById.
If you want to select by tag name, it's getElementsByTagName. If it's class names you want, getElementsByClassName (newer browsers only). You see? So use the right method depending on what you're selecting by.

Check one checkbox when other is selected [duplicate]

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

How to get the value of textbox using id in javascript

I want to get the value of input boxes based on id and name.
Since my id is having comma its not accepting. When i remove comma and one of the id,it shows perfectly.
But, I will get the id as "Text,Demo_1" only. How can i get the value based on this id??
here is the code
HTML
<div id="Text,Demo_1" class="span12">
<label>Notes or Concerns</label>
<div class="control-group">
<input type="text" value="hi" name="view1" class="recommend">
<input type="text" value="hi2" name="view1" class="recommend">
<input type="text" value="hi3" name="view1" class="recommend">
</div>
</div>
Js part
$(function() {
var values = $('#Text,Demo_1 input[name="view1"]').map(function() {
return this.value;
}).get();
alert(values);
});
Get value by Name :
$("[name='view1']").val()
Get value by ID :
$("#[textbox_ID]").val()
Get all text values in array
var inputTypes = [];
$('.control-group input[name="view1"]').each(function(){
inputTypes.push($(this).val());
});
Use an array,
$(function () {
var values = [];
$('#TextDemo_1 input[name="view1"]').each(function () {
values.push($(this).val());
});
console.dir(values);
});
You should escape your comma with \\
var values = $('#Text\\,Demo_1 input[name="view1"]').map(function () {
return this.value;
}).get();
Demo: http://jsfiddle.net/M8Jmz/
But while it works you should consider changing an id to a proper identifier.
Use jQuery selectors to match the begining and end of the ID:
var values = $("div[id^='Text'][id$='Demo_1'] input[name='view1']").map(function() {
...
Edit: Explanation.
[id^='Text'] => Every element which id starts with "Text"
[id$='Demo_1'] => Every element which id ends with "Demo_1"
Putting them together will select every element that match both rules.
var values = $('input[name="view1"]').val();

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

keep checkboxes checked after page refresh

I have a couple of checkboxes. when any of them are clickd/checked and the search button is clicked, will grab their values and pass to the url as querystring and refresh the page returning results matching the passed query values.
like this: mysite.com/result.aspx?k="Hospital" OR "Office" OR "Emergency"
I am able to grab the values after 'k='. I have "Hospital" OR "Office" OR "Emergency" captured and stored in a variable. Now I need to reset the checked state of checkboxes based on these values after the page reloads and forgets the previous state of the controls. I couldn't move any further than this. Can someone help me?
var checkedOnes=decodeURI(location.href.match(/\&k\=(.+)/)[1]);
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
}
This is how I am capturing the checkboxes values and passing to the URL:
var checkboxValues = $("input[name=LocType]:checked").map(function() {
return "\"" + $(this).val() + "\"";}).get().join(" OR ");
window.location= url+checkboxValues;
<div class="LocTypeChkBoxesSearch">
<div class="LocTypeChkBoxes">
<input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS  
<input name="LocType" type="checkbox" value="Office"/> PHYSICIAN OFFICES  
<input name="LocType" type="checkbox" value="Emergency"/>EMERGENCY CENTERS  
<input name="LocType" type="checkbox" value="Out-Patient"/>OUT-PATIENT CENTERS  
<input name="LocType" type="checkbox" value="Facility"/>FACILITIES
</div>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit" ><span>GO</span></a></div>
</div>
I've faced same problem, and my solution is HTML5 Local Storage.
Add an function for colect checkboxes values
function(){
var data = $('input[name=checkboxName]:checked').map(function(){
return this.value;
}).get();
localStorage['data']=JSON.stringify(data);
}
And onload function to check checkboxes
function(){
if(localStorage&&localStorage["data"]){
var localStoredData=JSON.parse(localStorage["data"]);
var checkboxes=document.getElementsByName('checkboxName');
for(var i=0;i<checkboxes.length;i++){
for(var j=0;j<localStoredData.length;j++){
if(checkboxes[i].value==localStoredData[j]){
checkboxes[i].checked=true;
}
}
}
localStorage.removeItem('data');
}
}
It's work fine to me.
You shouldn't need JavaScript for this. You can check the $_GET parameters in your back-end code, and serve the page with the proper form element attributes.
In PHP, for example:
<input name="LocType" type="checkbox" value="Facility" <?php if (isset($_GET['LocType'] && $_GET['LocType'] == 'Facility') { ?> checked="checked" <?php } ?> /> FACILITIES
Try this.
//Split the url parameter value and get all the values in an array
var checkedOnes = decodeURI(location.href.match(/\&k\=(.+)/)[1]).split(" OR ");
//Find all the checkbox with name="LocType" and cache them in local variable
var $checkBoxes = $('input[name=LocType]');
//Loop through the array and find the corresponding checkbox element using filter
$.each(checkedOnes, function(i, val){
$checkBoxes.filter('value=[' + $.trim(val.replace(/\"/g, '')) +']').prop('checked', true);
});
I am splitting the value of k by OR which will give all the values in an array. Next, loop through the array and find the corresponding checkbox by matching its value attribute and set its checked property to true using prop method.

Categories

Resources