Jquery - How can I check if all of the checkboxes are unchecked? - php

For some reason my code doesn't work?! I need to check checkboxes, if all are "unchecked", then enable hidden field and send value to db, so I can identify that checkboxes were unchecked.
Question 1: Why isn't my jquery code working?
Question 2: I need to record checked or unchecked values to DB. My plan is to check if none selected in php. Is this a good practice?
HTML
<tr class="more_info">
<th valign="top">Other options:</th>
{foreach from=$HTML_cOPTIONS key=dbname item=optname}
{if ! empty($CARINFO[car].{$dbname})}
<td><input type="checkbox" id="forced_checkbox" name="c_options[]" value="{$dbname}" checked/> {$optname} </br></td>
{else}
<td><input type="checkbox" id="forced_checkbox" name="c_options[]" value="{$dbname}"/> {$optname} </br></td>
{/if}
{/foreach}
<input type="hidden" id="forceSendCheckBox" name="c_options[]" value="nocheckboxes"/>
<input type="button" value="Check" id="check" />
</tr>
Jquery
$('#check').bind('click',function()
{
if ($('#forced_checkbox').filter(':not(:checked)').length == 0) {
console.log('at least one checked');
$("#forceSendCheckBox").prop('disabled',true);//do not send this field to DB
} else {
console.log('nothing checked');
$("#forceSendCheckBox").prop('disabled',false);//send empty checkboxes
}
});
UPDATE
Here's a fiddle, it still seems to be broken. :-/
http://jsfiddle.net/L5J96/

IDs have to be unique. Use a class instead.
In your fiddle you had several problems. First, you forgot to select the jQuery framework from the menu, so none of the jQuery code worked. Second, you changed the filter from not(:checked) to (:checked), but didn't change == 0 to > 0. Third, without the not, you shouldn't have parentheses around the filter selector. Fourth, you tried to display the message in an input field using .text(), but the correct method is .val().
Here's the corrected code:
$('#check').on('click', function () {
if ($('.forced_checkbox').filter(':checked').length > 0) {
$('#forceSendCheckBox').val('at least one checked');
} else {
$('#forceSendCheckBox').val('nothing checked');
}
});
FIDDLE

As Barmar mentioned, the IDs must be unique.
Next, use .on() instead of .bind() - similar syntax, so easy to do. (.bind is deprecated)
However, to answer your question, you can quickly discover which checkboxes were not checked by selecting all unchecked checkboxes and iterating through them.
If you need to create a list of which checkboxes were unchecked, then you need something unique about each one (if every man in the room is named 'Bob', then making a useful list of all the men with brown hair will be difficult). Use the ID attr for that, as in the jsFiddle example at bottom.
$("input:checkbox:not(:checked)").each(function() {
alert($(this).attr('id'));
});
jsFiddle here
Here is an expanded jsFiddle example that demonstrates how to save the list of unchecked checkboxes into a hidden field, as requested in your post.
With respect to your jsFiddle, the following things needed adjusting:
See revised jsFiddle
Use of the .on() syntax. Use .on(document) or .on(body) instead:
$('document').on('action', '#elementID', function() { //Do stuff here });
In order to interate through the collection of unchecked objects, you should use jQuery's .each() method.
$('.forced_checkbox').filter(':not(:checked)').each(function() { //Do stuff });
Hope this helps.

Related

PHP/JavaScript check/uncheck working in FF but not working in IE

I got stuck with a simple piece of functionality which seems not to work on different browsers.
My need is to have a single checkbox (master checkbox) with a function to check/uncheck other checkboxes (children checkboxes). When the master checkbox is clicked, it's own state has to be transferred to a list of other checkboxes.
For example: If the master checkbox is not checked and gets clicked (and therefore selected), all the child checkboxes should get selected as well.
The code below works excellent in Firefox 13.0.1, but not in Internet Explorer 9.
All the code below is in the same file:
JavaScript
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('cb[]');
for each(var checkbox in checkboxes)
checkbox.checked = checkbox.checked == true ? false : true;
}
</script>
The Checkbox which is clicked for check and uncheck
<td width="3%"><input name="cb_all" type="checkbox" id="cb_all" onClick="toggle(this)"></td>
One single row
<td><input name="cb[]" type="checkbox" value="<?php echo $user->id;?>" id="cb[]"></td>
I like to believe that the solution should be a simple one, but after spending half a day of searching it would be very nice to have some help. Can you please help me with this one?
It is because Internet Explorer doesn't have a method called getElementsByName . The workaround is to use getElementsByTagName and check each one, you can get more information at http://webbugtrack.blogspot.com/2007/08/bug-411-getelementsbyname-doesnt-work.html

Changing the value of the checkboxes via jQuery

I have a few checkboxes in my form and I need to change their value when the checkbox is checked.
For example this is one of the checkboxes:
<input type="checkbox" name="drink" value=""/>
I know .val() can change it but I wasn't able to do this with if statement.
I appreciate your answer in advance.
What you are seeking is actually very meaningless. See, when a form is submitted, only the checked checkboxes actually send values, so it makes no sense to change the value especially for the unchecked checkbox.
Better Solution
You should instead give it the "checked" value, and keep it that way, that will cause it to submit correctly even without changing the values.
You can add a click event listener on the checkbox:
$('input[name="drink"]').click(function() { // when click on it
if ($(this).attr('checked')) { // if the checkbox is checked
$(this).val("value #1"); // change the value
} else { // otherwise if is unchecked
$(this).val("value #2"); // change the value
}
});
// attach an onchange handler to all checkboxes on the page
$("input[type='checkbox']").change(function() {
// or if($(this).prop("checked")) {
if(this.checked) {
$(this).val("value for checked");
} else {
$(this).val("value for unchecked");
}
});
The onchange event is the one you should be interested when it comes to checkboxes, as it fires whenever you change the checked state of it.
The checked property determines whether or not the checkbox has been checked.
The .val() method allows you to conveniently read/write element values.

jquery - select all checkboxes with js array name

I want to use a JQuery "check all" function in a form like this:
http://jetlogs.org/jquery/jquery_select_all.html
My problem is I am generating my form from a php script, and I don't know exactly how many checkboxes I will have in advance.
I use the "array" naming convention to be able to get all the selected checkbox values in my $_POST data...
so my checkboxes are like that:
<input type="checkbox" name="items[]" value="<?php echo $id ?>">
but this JQuery declaration does not work:
$("input[#name=items[]]").each(function()
{
this.checked = checked_status;
});
probably because the "[]" at the end of my "items" messes up the JQuery declaration... I tried to write #name=items[] like that: "#name=items[]", and to put some anti-slash before the [ and ] so they're not considered as special characters but it didnt work...
If someone knows a solution and is willing to share it'd be great!! :)
Escape internal brackets with \\(no space) - it should fix the problem.
This selector works for me:
$('input[name=items\\[\\]]')
Try using
$('input[name="items[]"]')
No need for # and use ". Note that the selector outside quotes are '. Otherwise you might cause parse error.
First of all, your name attribute should be used to set +1 elements with the same name. It's practically the same as the id attribute and should be unique per element excepted for references, but that is not the case for you.
Try using the class attribute, it's made for the things you want to do!
another thing is that in your code, you can only set your checkboxes to 'checked', but never to uncheck, this code will set your checkboxes to checked true or false, according to what it gets as attribute from the clicked element.
you can do something like this:
set your check all checkbox with an id
<input type="checkbox" id="checkAll">
Then set on all checkboxes that should be checked/unchecked a class
<input type="checkbox" class="checked">
And the you can do something like this in jQuery
$("#checkAll").click( function(){
var checkedValue = $(this).attr("checked");
$("input.checked").attr("checked", checkedValue); });
this will change all checkboxes with class checked to the same checked attribute as the one with id checkAll
$("input[name='smsid[]']")
This code works fine for me...

Enumerate all Check Box in PHP

I have web page in PHP which displays all records in a table. I want to add check boxes against all rows and user can check a check box to select a row and then submit the page. When the page is submitted I want to enumerate all check boxes and check whether they are checked or not, How can I do this?
You'll create your checkboxes like this:
<input name="rows[]" value="uniqueIdForThisRow" type="checkbox" />
<input name="rows[]" value="anotherId" type="checkbox" />
Then you can loop through them like this:
<?php
// $_POST['rows'] contains the values of all checked checkboxes, like:
// array('uniqueIdForThisRow', 'anotherId', ...)
foreach ($_POST['rows'] as $row) {
if ($row == 'uniqueIdForThisRow') {
// do something
}
}
?>
PHP docs on dealing with forms, see especially Example #3.
Creating the form
You can generate the HTML as follows:
<form [action, method etc]>
<table>
<?php
foreach($dataSet as $dataRow) :
?>
<tr>
<td>
<input type="checkbox" name="dataRow[]" value="<?=$dataRow['id']?>"/>
</td>
[Additional details about datarow here]
<tr>
<?php
endforeach;
?>
</table>
</form>
AFTER POST
look into $_POST['dataRow'] : this will be an array with values the IDS of your $dataRow, so using array_values on $_POST['dataRow'] will give you all the ids of the selected rows:
<?php
$checkedRows = array_values($_POST['dataRow']);
foreach($checkedRows as $row) {
// Do whatever you want to do with the selected row
}
You don’t have to check all checkboxes if they have been checked. Because only successful controls are send to the server. And a checkbox is only successful when it’s checked:
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
So you just have to look what checkboxes you get in the request at all. And if you want to use <select multiple>, take a look at How do I get all the results from a select multiple HTML tag? in the PHP FAQ.
if i were you... i wouldn't fight with altering html table structure.
you can handle that with Javascript frameworks like JQuery which is very effective solution for you. you deal only a few lines of JS code and you don't need exaggerate the html output (i guess it's probably long enough). about jquery there is a good source named visual jquery if you have never used that.
here is the way how to do that.
you dont need to edit inside the loop. you just only put an id to your table tag.
then add new column to your table with checkboxes inside.
then you can get the values of checkboxes & serialize them in to a hidden input. or you can handle selected rows with ajax easy. i think JS framework will work better.
normally i've added many links to post but it says it's not allowed for new users.

JQuery help with checkboxes and their values

I am very new to javascript and JQuery but I managed to get my first ajax script almost working 100%. Maybe today will be my lucky day and I can finish this up. :)
Let me give you guys a sample of each file so you know what is what. I believe that my last try at figuring this out was not successful because I was confusing these files. They are all js and have the exact same syntax.
What I have are 2 javascript files. One is called ajax.js and has the folling syntax. it calls ajax.php.
$("#admEmpID").bind("change", function(e){
$.getJSON("ajax.php?e=" + $("#admEmpID").val(),
function(data)
{
$.each(data, function(i,item)
{
if (item.field == "admEmpStatus")
{
// ?? radio buttons
}
............. etc
The next file I have is this script and is called admEmp.js. I think that this one is for my form validation.
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".admEmpBtn").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var admEmpID = $("input#admEmpID").val();
var admEmpStatus = $("input[name='admEmpStatus']:checked").val();
$.ajax({
type: "POST",...............etc.
What I would like to do is toggle my checkboxes according to the database results. If the result from the database is = 1 then the checkbox should be checked otherwise it should be unchecked.
These scripts that I have in place now will populate my textboxes from the values in the database so for someone like myself who has no idea what is happening with JQuery and its innerworkings, it is only natural for me to assume that the checkboxes will also be filled with the on/off values. Maybe I am incorrect. The last time I posted on SO looking for help, a guy mentioned that I needed to toggle the results with server side code. Is this correct or will JQuery do it for me?
I also have radio buttons in addition to the checkboxes that I need to show the values for as well. Just as a side note, the checkboxes are not grouped; they each have their own value.
Thanks for any help you guys can provide.
OK. "dz" said that I should put ('#admCustRptDly').attr('checked', true); into my script to see if that will allow me to see the checked attribute but it doesn't. The database has a 0 for that checkbox so I sould be seeing no checkmark. I put that into the ajax.js file. Here is what it looks like now.
else if (item.field == "admCustRptDly" && item.value == "1")
{
// $("checkbox#admCustRptDly").attr("checked", "checked");
$('#admCustRptDly').attr('checked', true);
}
Here is what I did that makes me think that I may be making some progress. I put an alert inside of the condition and I do NOT get an alert. If I go to a customer that does have the db value set to 1, then I do get the alert. That's more than I was getting before. But again, I am still seeing the checkmark even though the data in the db = '0'
Checkboxes behave a little differently than other input fields. When you have <input type="text" name="field1" value="foo" /> for example, the text field is automatically populated with "foo".
However, if you have <input type="checkbox" name="field2" value="1" />, the checkbox doesn't have anything to populate. This is because the checkbox has a special "checked" attribute that determines whether or not it is checked by default. As such, it's very possible your script that populates your textboxes are putting in the correct value for the checkbox, but are not setting the checked attribute.
To do so with jQuery, you can do $('#checkboxid').attr('checked', true);.
If I understand correctly, you have a form that is updated asynchronously via an Ajax call when you change the value in the #admEmpID field (first js file).
The second js file contains code to post changes you made to the form back to the server. I don't think it's for form validation (at least not the part you're showing).
But I'm not sure what the problem is. The first js file gets data from the server when you change some text field (#admEmpId). Is that data not shown correctly? You mention that textboxes are filled with the correct data. Are the checkboxes and radiobuttons not selected when they should be? In that case, you must first make sure you understand what data is returned from the server (contained in the data variable in the first js file). Then you must verify that the script addresses the right elements on your page to be updated.
You may just need another else if clause in your javascript for the case when you want to uncheck a box:
else if (item.field == "admCustRptDly" && item.value == "0")
{
$('#admCustRptDly').attr('checked', false);
}
You could, however, simplify both cases into a single statement like so:
else if (item.field == "admCustRptDly")
{
$('#admCustRptDly').attr('checked', ((item.value == "1") ? true : false));
}

Categories