jquery - select all checkboxes with js array name - php

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...

Related

get selected checkbox values into jQuery and process to the other page

I need help with the jquery. Im just starting on how to code with jQuery so im kinda newbie. please help me with some solutions,
so far i have this in the markups
<input type='checkbox' data-headmark=".$row['HEAD_MARK']." data-id=".$row['ID']." class='cuttingCheckbox' name='cuttingCheckbox'/>
and the jquery i have so far is just disabling the checkbox once selected,
$('.cuttingCheckbox').change(function() {
if (this.checked) {
this.setAttribute("disabled", true);
}
});
and the page who is going to use the values is the database process,
oci_parse($conn,"UPDATE FABRICATION_QC SET CUTTING = 'Y'
WHERE HEAD_MARK = ".$_POST["headmark"]." AND ID = ".$_POST["headmark_id"].";");
so the idea is sending those two values from checkbox to another page dynamically
Thanks guys for helping me
The answer to this question depends on if you want to send that update to the database life (I.E., right when the checkbox is checked) or on the form submit.
If live, you will use Ajax to immediately post the data. If not live, you will likey (in the jQuery) have to add something like so:
if (this.checked){
this.setAttribute("disabled", true);
var hidden=document.createElement("input");
input.type="hidden";
input.name=this.getAttribute("data-headmark");
input.value=this.getAttribute("data-id");
document.body.appendChild(input);
}
That way, an input of type "hidden" is added so when the form is posted, you can retrieve the variables stored in $_POST. If you need to keep track of what those variables are, you could use a similar method to append to a hidden input with a fixed name.

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

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.

how to get checkbox values in javascript

i want to set more value to checkbox,how do it? this is my code: from this code only i could get upto 3 value,why? i want to get 5 value.how do it?
$results=$watch.",".$thumbnail.",".$name.",".$description.",".$val;
<input type="checkbox" name="checkbox[]" id="checkbox[]" class="addbtn" value=<?php echo $results;?>
javascript fn:
function chkbox()
{
$('[name^=checkbox]:checked').each(function() {
var ckballvalue=($(this).val());
var latlngStrs = ckballvalue.split(",",5);
var link = latlngStrs[0];
var thumbnail = latlngStrs[1];
var name = latlngStrs[2];
var description = latlngStrs[3];
var categ = latlngStrs[4];
alert(link+thumbnail+name+description+categ);
}
Assuming your markup is correct and you're using POST, then you just grab them from the $_POST variable in PHP.
$checkedValues = $_POST['checkbox'];
This will be an array of all checked values, where 'checkbox' is the name of your input group.
When a browser posts a form containing checkboxes, it only posts anything for the checkboxes that have been checked. The ones that are unchecked will not be sent at all.
Therefore, if you have five checkboxes, but only three are checked, your PHP $_POST or $_GET array will only contain entries for those three, not the other two.
This will also means that if you're using name="checkbox[]" for all your checkboxes, then your array elements will not be numbered as you expect.
Note that this is the way HTML forms work; it's got nothing to do with PHP.
If you want to force it, you could have a hidden field on the form which mirrors the checkbox state using Javascript. This way you'll be certain you'll always get the value posted to you whether it was checked or not.
Or you could just accept the way it works. You may not get the values posted to you if they aren't checked, but their absence is sufficient, as not having those field posted allows you to know that they weren't checked.
You might find it helpful to give your checkboxes explicit array element keys -- ie rather than name="checkbox[]", use name="checkbox[3]". This way they'll always be posted into the right slot in your $_POST array.
Hope that helps.

Using jQuery to fill out a form element but value not passing to form action

All
I have the following form input element:
<input name="payment_amount" type="text" id="payment_amount" value="" disabled>
I then manipulate the value of this form element by using jQuery:
jQuery(document).on('click','#remaining_balance',function(){
jQuery("#payment_amount").attr('disabled', 'disabled');
send_amount = jQuery("#value_to_transfer").val();
jQuery("#payment_amount").val(send_amount);
});
When I click on that radio button it populates the value into my payment_amount field but when I submit the form the value doesn't get passed to my receiving page. Any idea why that it?
Thanks in advance.
Disabled elements are not sent to the server. Enable it, send the data, then disable it again.
From this site:
http://webdesign.about.com/od/forms/a/aa071805.htm
I can see that "the disabled element will not be successful when submitting the form"
So, disabled form-fields aren't sent
Your jquery code isn't *un*setting the disabled field, so you're setting the value, sure. But you're not sending it.
SOLUTION:
// To enable
$('#payment_amount').removeAttr('disabled');
// OR you can set attr to ""
$('#payment_amount').attr('disabled', '');
(i got that code snippet from
http://jquery-howto.blogspot.com/2008/12/how-to-disableenable-element-with.html)
ADDED BONUS:
your jquery hurt my eyes. Why not use
$('#remaining_balance').click( function(){
...
}
Actually, why aren't you using the $ operator at all? Um, you use it instead of the "jquery" keyword.
So, that said, the solution you'd want is (if you want to keep on not using the $ operator):
jQuery("#payment_amount").removeAttr('disabled');

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.

Categories