background
I have a table grid of checkboxes, grouped by name, and each checkbox contains a time value. An example of the HTML:
<td><input type="checkbox" name="tuesday[]" value="10am"></td>
<td><input type="checkbox" name="tuesday[]" value="11am"></td>
<td><input type="checkbox" name="tuesday[]" value="12pm"></td>
<td><input type="checkbox" name="tuesday[]" value="1pm"></td>
<td><input type="checkbox" name="tuesday[]" value="2pm"></td>
<td><input type="checkbox" name="tuesday[]" value="3pm"></td>
<td><input type="checkbox" name="tuesday[]" value="4pm"></td>
<td><input type="checkbox" name="tuesday[]" value="5pm"></td>
<td><input type="checkbox" name="tuesday[]" value="6pm"></td>
<td><input type="checkbox" name="tuesday[]" value="7pm"></td>
When the form is submitted, the values are POSTed how I want them to be; all the checked times are in the tuesday[] array.
problem
I want to do some client-side validation with jQuery. I want to check that at least one checkbox is checked.
I have tried storing it into a var like so:
var availTuesday = $("input:checkbox[name='tuesday']:checked");
But when I do so and the console.log(availTuesday);, nothing is shown (regardless on if something is checked or not). I have also tried console.log(availTuesday.serialize());
Question:
how can I retrieve the user-checked values for the tuesday[] checkbox group, as well as for the other dates (wednesday[], thursday[], etc)?
Thank you.
The selector is not correct, change it to:
var $tuesday = $("input[type=checkbox][name='tuesday[]']:checked");
For getting the values you can use .map() method which returns an array:
if ($tuesday.length) {
// Getting values of the checked checkboxes
var values = $tuesday.map(function(){
return this.value;
}).get();
// ...
} else {
// There is no checked `day[]` checkbox
}
In case that you have other similar set of checkboxes you can use an array:
var days = ['days', 'in', 'a', 'week'],
values = {},
errors = [],
$checkboxes = $("input[type=checkbox]");
$.each(days, function(_, day) {
var $set = $checkboxes.filter('[name="'+day+'[]"]:checked');
if ($set.length) {
values[day] = $set.map(function() {
return this.value;
}).get();
} else {
// There is no checked `day[]` checkbox
errors.push(day);
}
});
if (errors.length) {
// console.log('Please check at least one hour in ' + errors.join(', ') + ' days ...');
} else {
// console.log(values);
}
You can try
var availTuesday = [];
$('input[type=checkbox][name="tuesday[]"]:checked').each(function() {
availTuesday.push($(this).val());
});
JSFiddle
If you want the actual value
var values = $("input[type=checkbox][name='tuesday[]']:checked").map(function() {
return this.value;
}).get();
If all you are really after is if any boxes are selected you can do the following:
if($('input[type="checkbox"][name="tuesday[]"]:checked').length) {
...
} else {
...
}
The length value is a property of the jQuery object (superset of DOM object) that specifies how many nodes matched the selector. In this case, if you check the length and the value is 0, no :checked checkboxes with the name tuesday[] exist (i.e. the user has not checked any boxes so display your validation message). It's quick and dirty validation. If you're looking to retrieve the values, the multitude of other answers are probably better.
You'll need to fix the selector to match the name, as others have mentioned.
If you just want to test that one is checked, you can go straight to a boolean, like this:
var availTuesday = $("input:checkbox[name='tuesday[]']:checked").length > 0;
Related
Well, I have this text input that gets sum of all the attributes of "price" inside all checkboxes are checked.
now i can't get an attribute value from a checkbox.
here is my function:
function sum_options() {
var options = [];
$("#form-field-1-11-1").attr("price", 500);
$("#form-field-1-11-2").attr("price", 500);
$("#form-field-1-11-3").attr("price", 0);
$("#form-field-1-11-4").attr("price", 300);
$("#form-field-1-11-5").attr("price", 500);
$("#form-field-1-11-6").attr("price", 500);
$("#form-field-1-11-7").attr("price", 1250);
$("#form-field-1-11-8").attr("price", 500);
$("#form-field-1-11-9").attr("price", 700);
options[0] = $("#form-field-1-11-1");
options[1] = $("#form-field-1-11-2");
options[2] = $("#form-field-1-11-3");
options[3] = $("#form-field-1-11-4");
options[4] = $("#form-field-1-11-5");
options[5] = $("#form-field-1-11-6");
options[6] = $("#form-field-1-11-7");
options[7] = $("#form-field-1-11-8");
options[8] = $("#form-field-1-11-9");
var total = 0;
$.each(options, function() {
this.on("change", function() {
total += this.attr("price");
});
});
$("#sum-field").val(total);
}
thanks!!!
Your code is a lot more complex than it needs to be.
Firstly, you should use data-* attributes to assign custom data to an element. Creating your own non-standard attributes will mean your HTML is invalid and can lead to other issues. Also, if your code is relying on the price attribute, then it should be in the DOM when the page loads.
Secondly there's no need to build an array of single elements. You can select them all in to a single jQuery object and set a change() event handler on them in a single call. I grouped them by class in the below example.
Lastly you can get the total of all the prices by looping through the :checked boxes and adding up their prices. Try this:
$('.checkbox').change(function() {
var total = 0;
$('.checkbox:checked').each(function() {
total += parseFloat($(this).data('price'));
});
$("#sum-field").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="form-field-1-11-1" class="checkbox" data-price="500" />
<input type="checkbox" id="form-field-1-11-2" class="checkbox" data-price="500" />
<input type="checkbox" id="form-field-1-11-3" class="checkbox" data-price="0" />
<input type="checkbox" id="form-field-1-11-4" class="checkbox" data-price="300" />
<!-- other checkboxes here... -->
<input type="text" id="sum-field" />
To get the value of the Value attribute you can do something like this:
$("input[type='checkbox']").val();
Or if you have set a class or id for it, you can:
$('#check_id').val();
$('.check_class').val();
However this will return the same value whether it is checked or not, this can be confusing as it is differnt to the submitted form behaviour.
To check whether it is checked or not, do:
if ($('#check_id').is(":checked"))
{
// it is checked
}
You just forgot to parse the return value to a number:
parseInt(this.attr("price"));
the attr() function is returning a string value.
I am really new to Javascript and know absolutely nothing about JQuery, so I apologize now for my newbie status.
I have an array of checkboxes (up to 18) that have the same name and class (can't change that fact):
<input type="checkbox" name="elective_id[]" value="112" class="elective_id">
<input type="checkbox" name="elective_id[]" value="128" class="elective_id">
<input type="checkbox" name="elective_id[]" value="135" class="elective_id">
<input type="checkbox" name="elective_id[]" value="322" class="elective_id" onClick="checkSister(322);">
<input type="checkbox" name="elective_id[]" value="323" class="elective_id" onClick="checkSister(323);">
Within that array will be 3 pairs of checkboxes that need their counterpart checked/unchecked when their pair is checked/unchecked. The three pairs are 320,321 & 322,323 & 345,346.
If checkbox with value 322 was selected, how can I automatically select the pair?
function checkSister(brother) {
if (brother=="322") {
document.getElementById("322").checked = true;
document.getElementById("323").checked = true;
} else if (brother=="322") {
document.getElementById("322").checked = true;
document.getElementById("323").checked = true;
}
}
I know that is not right, but haven't figured out how to get the right variable selected, let alone deselected.
Any help you can provide would greatly be appreciated,
Jim
You can do it easily without jquery using querySelectorAll
document.querySelectorAll("input[type='checkbox'][value='112']")[0].checked=true;
or you can query by name and value like this:
document.querySelectorAll("input[name='elective_id[]'][value='112']")[0].checked=false;
To convert that vanilla JavaScript to jQuery,
function checkSister(brother) {
if (brother=="322") {
$("#322").prop("checked") = true;
$("#323").prop("checked") = true;
} else if (brother=="322") {
$("#322").prop("checked") = true;
$("#323").prop("checked") = true;
}
}
There are checkboxes, which belong to Form A:
<input type="checkbox" class="item-selector" name="item[]" value="1" />
<input type="checkbox" class="item-selector" name="item[]" value="2" />
<input type="checkbox" class="item-selector" name="item[]" value="3" />
<!-- etc. -->
Then I have Form B that needs the checkbox values from Form A. Form A might have other input fields too, but I'm not interested in those. I only care about $('input.item-selector'). I'm going about it like this:
var postData = $('#form-a').serializeArray();
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
if(items.length > 0) {
postData.push({name: 'itemId', value: items});
}
But this way of adding stuff to the postData doesn't seem to work, because the PHP script I send the form to can not find the itemId. Interestingly this does work:
postData.push(name: 'aName', value: 'notAnArrayButAStringValue');
I also tried a couple of solutions like this one: http://benalman.com/projects/jquery-misc-plugins/#serializeobject but the problem with them is that, while they otherwise work fine, for some reason if there are checkboxes in Form B, the checkbox values of Form B are parsed incorrectly and result in null values and loss of data. That would look like this:
var postData = $(this.form).serializeObject();
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
if(items.length > 0) {
postData.itemId = items;
}
Using JSON.stringify revealed the object structure to be like this:
{
"name":"Simon J. Kok",
"address_id":"39669",
"email":"*****",
"content_id":"21921",
"client_id":"42101",
"is_ebill":["","1"], <-- this is a checked checkbox
"is_banned":"", <-- this is an unchecked checkbox
"button":"save"
}
The checkboxes in Form B look like
<input type="checkbox" value="1" name="is_ebill" />
<input type="checkbox" value="1" name="is_banned" />
So what I need is either some insight on how to add the checkboxes from Form A to the $.serializeArray() result array -OR- a way to solve the issue of a checked checkbox returning an array when using Ben Alman's plugin.
Here's one approach. First it requires a hidden field in form-b:
<input type="hidden" id="itemId" name="itemId" value="" />
This would be populated with the item-selector data when the form is submitted:
$('#form-b').on('submit', function() {
var checkedValues = [];
$('.item-selector:checked').each(function() {
checkedValues.push($(this).val());
});
$('#itemId').val(checkedValues.join(','));
console.debug('Form B data:', $('#form-b').serializeArray());
});
Adjust the syntax to suit your idiom. Here's a fiddle to demonstrate:
http://jsfiddle.net/klenwell/12evxfvc/
Actually I kinda answered my own question already when I asked it. I used JSON.Stringify to output the JSON formatted string of what $.serializeArray() returned and it became apparent what the structrure needed to work. So here is how to add array values one by one to an array retrieved using $.serializeArray():
var items = $('.item-selector:checked').map(function(){
return this.value;
}).get();
$.each(items, function(i, v){
postData.push({name: 'itemId[]', value: v});
});
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;
});
}
});
I have several checkboxes and a fake submit button to make an AJAX request:
<form>
<input type="checkbox" value="1"/>
<input type="checkbox" value="2" checked="checked"/>
<input type="checkbox" value="3"/>
<input type="checkbox" value="4" checked="checked"/>
<input type="button" onclick="return mmSubmit();"/>
</form>
Within the mmSubmit() method, I would like to retrieve an array of values that have been selected. Here is what I am currently doing.
mmSubmit = function() {
var ids = [];
$('input[type=checkbox]:checked');.each(function(index) {
ids.push($(this).attr('value'));
});
// ids now equals [ 2 , 4 ] based upon the checkbox values in the HTML above
return false;
};
I'm wondering if there is a shorthand method in jQuery used to retrieve the values into an array, or if what I have is already optimal.
I think this can be accomplished with map. Try the following..
mmSubmit = function() {
var ids = $('input[type=checkbox]:checked').map(function(){
return $(this).val();
}).get();
// ids now equals [ 2 , 4 ] based upon the checkbox values in the HTML above
return false;
};
Take a look at: jQuery Traversing/Map
Well you can use .val() instead of .attr('value').
$.serializeArray() may also do what you want (http://docs.jquery.com/Ajax/serializeArray).
It's needs some optimization, buts generally it is right way. My variant:
mmSubmit = function () {
var ids = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
ids[ids.length] = this.value;
}
});
return ids;
};
It's little faster.