Check all checkbox with an array - php

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

Related

How to check multiple checkboxes checked using jquery?

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

jQuery: second dropdown from array based on value of first dropdown

Question: I have two drop-down boxes. Using jQuery, I want to populate second drop-down box on selection of the first drop-down box (help with my existing code). I have marked the area I need help with in the jQuery code below, plus an explanation of what I want to achieve in "Code help".
I realise this is a VERY frequently requested item on SO and I have seen many comments that this can be done in simple JS, but since there are already other jQuery elements in use on the page (not coded by me) and for simplicity, I want to use JQ.
I am completely new to any jQuery code, I have researched many examples, however I am getting lost in the logic since I am not familiar with JS or JQ coding conventions, so keeping things simple is important so I can understand what is happening within the code (I am not just looking for help to get my code working, but also so I can learn and understand what is happening).
I found pretty much exactly the operation I want to achieve (except for one important point explained in "Code help" below) by following a tutorial here: http://jqueryfordesigners.com/populate-select-boxes/. A sample page showing the operation is here: http://jqueryfordesigners.com/demo/select-boxes.html
Code help: In the tutorial, the second dropdown is populated from the content of static html files in: $article.load('select-boxes-' + categoryName + '.html');
I need the second dropdown to be populated from the JS variable $st_list and the PHP variable $student_block based on the selected value in the first dropdown, as shown in my code below.
Could anyone please help with how to adapt the code to make that happen?
Thank you
My code:
For simplicity, the first dropdown is static with simple integer values, but will be populated from the DB in $test_seq in the working code with integer values same as the example code below (if that matters). Additionally, in a separate PHP process (later) the $test_seq, $student_id and other new variables will be used to send back data to the DB (included for reference only, though not relevant for this request).
select-boxes.php
$sql = "SELECT * FROM TBL_NAME";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$test_seq = $row['SEQ'];
$student_id = $row['st_num'];
$student_name = $row['st_name'];
$student_block .= '<OPTION value="'.$student_id.'">'.$student_id.' - '.$student_name.'</OPTION>';
}
Form:
<form action="select-boxes.php">
<label for="test_day">Test day:</label>
<select name="test_day" id="test_day">
<option selected value=""> </option>
<option value="1">Day 1</option>
<option value="2">Day 2</option>
<option value="3">Day 3</option>
</select>
<input type="submit" id="next" value="next »" />
</form>
jQuery:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
var $test_day = $('#test_day'),
$st_list = null;
$test_day.change(function () {
var test_dayVal = $test_day.val();
if ($st_list == null) {
$st_list = $('<select name="st_name" id="st_name"><?php echo $student_block; ?></select>').appendTo('form');
$next.remove();
$('form').append('<input type="submit" value="process »" />');
}
$st_list.load('#test_dayVal'); //<--I think this is where I need help.. What do I do here?
});
var $next = $('#next');
$next[0].setAttribute('type', 'button');
});
</script>

Collect checkbox values in jQuery and POST them on submit

I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>

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!

building a query string with jquery and checkboxes

I'm building a search form with several filter options on the results page.
It's a basic search form, results show in an friendly url such as: domain.com/resuts/country/age/type/
The filters are simply checkboxes which on click, should reload the page with a query string to identify what has been checked/unchecked. (there is no submit, preferably the update would rebuild the query string with every check box click).
So, for example, on click of some checkboxes we'd build a query string on the end,
eg:domain.com/resuts/england/20-29/female/?scene=hipster&status=single
Can anybody point me to a jquery resource or a code snippet which may assist in getting this done?
Many thanks,
Iain.
The jQuery.get function will automatically handle creating and building the query string when you pass a key-value pair:
http://docs.jquery.com/Ajax/jQuery.get
You can use this selector for checked checkboxes:
$('input:checkbox:checked')
If your html looks like
<input type="checkbox" name="scene" value="hipster" />
I guess you can use something like
var tmp = [];
$('input:checkbox:checked').each(function(){
tmp.push($(this).attr('name') + '=' + $(this).val());
});
var filters = tmp.join('&');
$('.checkbox_class').change(function () {
let filter = $('.checkbox_class');
let types = [];
$.each(filter, function( index, input ) {
if(input.checked)
{
types[index] = input.value;
}
});
let typeQueryString = decodeURIComponent($.param({type:types}));
console.log(typeQueryString);
});
Is this what your looking for? When you click the checkboxes it shows the selected values up top. when you submit the form it shows you the same value in an alert
<div id="buffer" style="height:2em; border:1px solid black; margin-bottom:1em"></div>
form action="#" method="get">
input type="checkbox" id="j" name="state" value="state">state
input type="checkbox" name="city" value="city">city
input type="checkbox" name="type" value="type">type
input type="submit" value="click me">
/form>
$().ready(function(){
//just a simple demo, you could filter the page by the value of the checkbox
$('form input:checkbox').bind('click',function(){
if($(this).attr('checked')==false){
//remove it from the query string
var pieces=$('#buffer').text().split('/');
var $this_val=$(this).val();
for(var i=0;i<pieces.length-1;i++){
//console.log($(this).val());
//console.log(pieces[i]);
if(pieces[i]==$this_val){
//remove value from the buffer
pieces.splice(i);
}
$('#buffer').text(pieces.join('/')+'/');
}
}else{
//add the value to the query string
$('#buffer').append($(this).val()+'/');
}
});
//on form submit
$('#filterWrapper form').submit(function(){
var queryString='';
$.each($('form input:checkbox:checked'),function(){
queryString+=$(this).val()+'/';
});
alert('this will get send over: '+queryString);
return false;//remove this in production
});
Sorry about the broken HTML, the editor doesnt like form tags and input tags

Categories