How to check multiple checkboxes checked using jquery? - php

i am new to the jquery, it is quite interesting, but i am having a little problem,
i am populating multiple checkboxes from database using foreach loop like this,
<? foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="city[]" />
<? } ?>
i want to restrict user to check atleast one checkbox, i know how to do this with only one checkbox, but got confused with this kind of array in jquery, any help will be greatly appreciated!
Many thanks in advance!

To find how many checkboxes are checked, you can use something like:
var checkedNum = $('input[name="city[]"]:checked').length;
if (!checkedNum) {
// User didn't check any checkboxes
}
Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').filter(":checked").
Finally, !checkedNum will only pass if checkedNum is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.
References:
jQuery attribute equals selector: http://api.jquery.com/attribute-equals-selector/
:checked selector: http://api.jquery.com/checked-selector/
jQuery .length property: http://api.jquery.com/length/

If you want at least one checkbox checked, you can use this
var somethingChecked = false;
$("input[type=checkbox]").each(function() {
if(this).is(':checked')) {
somethingChecked = true;
}
});
if(!somethingChecked) {
alert("You haven't checked anything yet");
}
What this does is initialize a variable to false. Then the script loops through all inputs of type checkbox. If the item is checked, set the variable to true. Finally, check if the variable is still false. If it is, then show an error.

This code work well for me,here i convert array to string with ~
<input type="checkbox" value="created" name="today_check"><strong>Created</strong>
<input type="checkbox" value="modified" name="today_check><strong>Modified</strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var vals = "";
$.each($("input[name='today_check']:checked"), function(){
vals += "~"+$(this).val();
});
if (vals){
vals = vals.substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>

Assuming you have #my_form as the ID of your form, you could do
$("#my_form input[type=checkbox]:checked"). // ... do something
to select and do something with the checked checkboxes. You can also do
$("#my_form input[type=checkbox]").each(function(idx, elem) {
var is_checked = $(this).prop("checked");
// Do something with is_checked
});
to iterate through all the checkboxes and check whether they are checked or not.

First of all id of the checkboxes should be unique.
Do like this
<?
$checkBoxCount = 0;
foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="chkbox-<?=$checkBoxCount?>" />
<? } ?>
Now in jQuery check like this to get all the checkboxes thats checked.
var checkCount = $("input[name='city[]']:checked").length;
if(checkCount == 0)
{
alert("Atleast one checkbox should be checked.");
}

Related

PHP dynamically created checkboxes with JQuery .toggle()

I have dynamically created an array of checkboxes in PHP for a form, but I don't want the Submit button to appear unless at least one checkbox is checked. Scouring the Internet most people who want the Submit button to only appear after checking a checkbox only have one "I agree" checkbox. Is it the dynamic creation that is preventing my script working?
PHP↴
// Dynamically create checkboxes from database
function print_checkbox($db){
$i = 0;
foreach($db->query('SELECT * FROM hue_flag') as $row) {
if ($i == 0 || $i == 3 || $i== 6 || $i == 9){
echo '<br><br>';
}
$i++;
echo '<span class="'.$row['1'].'"><label for="'.$row['1'].'">'.ucfirst($row['1']).'</label><input type="checkbox" name="hue[]" id="hue" value="'.$row['0'].'"></span> ';
}
}
jQuery↴
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hue[]').click(function(){
$('#input_gown').toggle();
});
});
</script>
PHP function call↴
<?php print_checkbox($conn_normas_boudoir);?>
Admittedly I know nothing about jQuery or JavaScript and am still learning PHP. So, if there's a better way to implement this, let me know.
You're giving all your checkboxes the same ID. That's not allowed; IDs have to be unique.
An easy solution to both problems is to assign all the checkboxes a common class:
echo '<span class="'.$row['1'].'"><label for="'.$row['1'].'">'.ucfirst($row['1']).'</label><input type="checkbox" name="hue[]" class="hue" value="'.$row['0'].'"></span> ';
Then select the class in jQuery:
$('.hue').change(function(){
$('#input_gown').toggle();
});
But that may give unexpected results; what if two checkboxes are checked? The #input_gown element will toggle on and off again. Perhaps you only want it shown if at least one checkbox is checked:
$('.hue').change(function(){
var val = false;
$('.hue').each(function() {
val = val || $(this).is(':checked'); // any checked box will change val to true
});
$('#input_gown').toggle(val); // true=show, false=hide
});
http://jsfiddle.net/mblase75/AyY3Z/
Your jQuery selector is looking for elements with id hue[]. But your elements have the id of just hue.
Change this:↴
$(document).ready(function(){
$('#hue[]').click(function(){
$('#input_gown').toggle();
});
});
to this (IDs should really always be unique, and the square brackets will need to be escaped to work with the selector engine), (a demo)):↴
$(document).ready(function(){
$('input[name=hue\\[\\]]').click(function(){
$('#input_gown').toggle();
});
});

Grab checkbox values before form submission

I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.

Javascript function only outputs value of first check box from a PHP for loop

I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com

Check all checkbox with an array

Trying to make the infamous checkall checkbox for dynamically created rows from a MySQL query. Rows (and therefore checkboxes) could range from 1 row to a metric buttload.
The form (without the checkall) is as follows:
<form name="form" method="post" action = "process.order.php">
<?php
while($fetch = mysql_fetch_array($order_query){
$order_id = $fetch['oid'];
$order_status = $fetch['ostat'];
?>
<input type="checkbox" name="order_row[<?=$order_id?>]" id="1" value="1">
<select name="status[<?=$order_id?>]" id="status[<?=$order_id?>]"
<option value="Ordered">Ordered</option>
<option value="Backordered">Backordered</option>
</select>
<? } ?>
<input type="submit" name="submit" id="submit" value="submit"> </form>
In process.order.php:
<?php
if(is_array($order_row)){
foreach($order_row as $order_id=>$val){
...followed by the rest of the script. I tried using this: How to implement "select all" check box in HTML?
and this:
Select All Checkbox
I'm trying to avoid using jQuery at this moment. Is there a way I can call the checkbox name generated by the PHP script into the javascript code?
Update:
I'd like to use a function that I can call across multiple pages. Thus, calling embedding the form name in the JS won't be practical for me. Also, I'd like it to be a checkbox - the button's worked great, but I'm trying to keep the UI simple and I already have a lot of buttons I'm trying to get rid of...
Working Example
You can do like this:
var frm = document.forms['form'];
for (var i = 0, l = frm.elements.length; i < l; i++) {
if (frm.elements[i].type === 'checkbox') {
frm.elements[i].checked = true;
}
}
Similarly, to uncheck all set:
frm.elements[i].checked = true;
to false.
You can also easily create checkAll and unCheckAll functions using above code.
By the way, an id with only numeric value is invalid, you should use alpha or mix of alpha and numeric characters.
If you don't have to support IE6 or 7, the following will work.
Live Demo
var checkAll = document.getElementById("checkall");
checkAll.onclick = function(){
[].forEach.call(
document.forms['form'].querySelectorAll("input[type='checkbox']"),
function(el){
el.checked=true;
});
}
​
​

Problem selecting multiple checkboxes

I am using a checkbox that has the name as "selectedids[]" and I am trying to select all checkboxes with the JavaScript. The code is not working. When I change the name of the checkbox to "selectedids" it works, but I can't do so because I need all the ids that are selected on the POSTED page.
The checkbox is as follows:
foreach($rows as $row)
{
<input type="checkbox" name="selectedids[]" value="<?php echo $row['id']; ?>" class="checkbox" />
........
........
}
And the Java-script function is as follows:
function SetAllCheckBoxes(CheckValue)
{
var CheckValue=true;
if(!document.forms['main'])
return;
var objCheckBoxes = document.forms['main'].elements['selectedids[]'];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
Please help me......
Thanks in advance.......
Do you have the option to use jQuery? If so, then you could do something like:
$(':checkbox').each(function(){
$(this).attr('checked',true);
});
It also might work to try:
$(':checkbox').attr('checked',true);
Or, if you just want to make sure all the boxes are checked only when the page first loads you could have your php that creates the checkboxes include "CHECKED". i.e.
<input type='checkbox' name='selectedids[]' value='value' CHECKED>
Updated to use :checkbox per comment
Why don't you just select them by id?
e.g.
var a=0;
while(document.getElementById('mycheckbox_'+a))document.getElementById('mycheckbox_'+a).checked=true;
If it was me, I would use the class of the checkboxes to identify them, with a bit of jQuery.
This would work:
$('input.checkbox').each(function(){$(this).attr('checked',true); });
It would set all checkboxes with class "checkbox" as true.
Beaten to it!

Categories