Ok, consider this problem. I have a list of email addresses and each email address has a checkbox which marks them as valid or not. OK, so the user can go and check/uncheck each one of the email addresses manually or he can click on a button that selects or deselects all the checkboxes.
However, my problem is, when the user clicks on that button that selects/deselects all the checkboxes, how would the program know in what state all the checkboxes are? I mean:
if (all checkboxes are checked)
{ uncheck all}
else
{ check all }
I cannot just go and take the value of the first row, since:
1. User may have checked/unchecked it manually
2. That ID may no longer be present in the db.
Please help me.
I think you are looking at this the wrong way. I would suggest having a checkbox as your toggle (as sites/apps do). Then the state of the checkbox is dependant whether all other checkboxes are selected.
You could do it with variables / flags but this look intuitive to me. here is an example - code is a bit rushed :)
http://jsbin.com/uyapi4
Just look at the first row, and then apply the opposite state to all checkboxes.
If there is an ID no longer in the database, that is a separate issue that you handle with server-side code, either by ignoring it, or by throwing a validatione error back to the user.
The way this is worded it makes me think this is a usability question as opposed to a programming question. Take a look at gmail and the ui they use for toggling selected emails. There is basically a checkall box at the top of the list which grays in checked if an email is checked. If you click it then it toggles everything to unchecked and switches to unchecked itself. If you click again it selects all. I think this UI works well.
Not sure if its what your are looking for, hope it help.
// Will select all checkbox input not checked, and checked them.
$(".checkbox-class:not(:checked)").attr('checked', true);
No tested.
Not entirely sure whether you're asking a UX question or a technical question. So I'll answer both. :-)
From a UX perspective, FWIW (and this may be off-topic), usually with an "all" button that toggles between "all" and "none", this is the state map I use:
all are checked => uncheck all
none are checked => check all
some are checked => check all
If you do that, this is really easy:
var cbs;
cbs = $(container).find('input[type=checkbox]');
cbs.attr('checked', cbs.not(':checked').length > 0);
Live example
...assuming all of these checkboxes are in some kind of container (e.g., a form or some div within the form, etc.).
If you want to do something else, you can still have jQuery to count the checked ones for you:
var cb, total, checked;
cb = $(container).find('input[type=checkbox]');
total = cb.length;
checked = cb.filter(':checked');
if (checked == total) {
// They're all checked
}
you can use this assuming you have all the checkboxes named email[]
Add this to the head of the page or in the script file you have:
<script type="text/javascript">
function checkAll()
{
checkBoxes = document.getElementsByName('email[]')
for(i=0;i<checkBoxes.length;i++)
if(!checkBoxes[i].checked)
checkBoxes[i].checked = true
}
function uncheckAll()
{
checkBoxes = document.getElementsByName('email[]')
for(i=0;i<checkBoxes.length;i++)
if(checkBoxes[i].checked)
checkBoxes[i].checked = false
}
</script>
and this in the body of the page:
Check All || Uncheck All
or add it as a button but dont forget to use"javascript:checkAll()"and"javascript:uncheckAll()"`
or store the state in a variable and do something like this?:
http://www.jsfiddle.net/EQuvq/12/
It sounds like you want two separate events: Select All and Deselect All. The most straightforward way to handle this is to have two separate buttons (or selections in a drop-down, whatever).
In this case, you'd want something like (in JavaScript using jQuery):
function selectAll() {
$(":checkbox").attr("checked", true);
}
function deselectAll() {
$(":checkbox").removeAttr("checked");
}
It's within the current HTML spec that the "checked" attribute have no value, but. If you're unsure about this, you can always use .attr("checked", true) instead.
If, on the other hand, you're looking for a function that toggles the state of each checkbox, then...
function toggleChecked() {
$(":checked").each(function() {
var checkedState = $(this).attr("checked");
$(this).attr("checked", !checkedState);
});
}
If, finally, you're looking for a function that assigns a checked state to all checkboxes, then...
function setChecked(state) {
$(":checked").attr("checked", state);
}
Related
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.
I am having a form with quite a lot of list boxes. After submitting the form I have no problem to process all list boxes with PHP in a loop. But I am looking for a way to only grab those that have changed because it would save a lot of processing time.
Let's say I have a hundred list boxes. Their ids are "lb_1" ... "lb_100". I would loop through them like:
foreach($_POST as $key=>$value) {
if (substr($key,0,3)== "lb_" ) {
...do something...
}
}
That loop however will do something with all the hundred listbox values. I only want to catch those that have actually changed.
Any ideas?
To expand on the suggestion given by #Tushar, you could use Javascript to set the Disabled attribute to true for any field that has not changed. That way they would not exist in the POST. The only way you would know which ones to disable is to store the initial values (in JS probably for ease of comparison). Then on form submit, loop through the fields and disable all the ones that have not changed.
document.getElementById('lb_1').disabled = true; // example of how to disable field
I can provide more example code if you like.
Ok, thanks to your tips I came up with this client-side solution:
I added a hidden form text field right before each listbox that contains the original value. The hidden field and the list boxed are named with the same unique suffix so I know which one belongs to which.
When the form is passed the PHP loop looks like this:
foreach($_POST as $key=>$value) {
if (substr($key,0,3)== "lb_" ) {
if ($_POST[hidden_name] != $value) {
setNewValue($value);
}
}
}
This is a lot faster than accessing the database for each compare since the values are already available in the $_POST array.
Thanks for your help.
This code is to work in combination with a form showing the results of the selections made on the right hand side of the page by loading the URL of the chosen option in a specified DIV that corresponds to the ID of the product.
function product_analysis(productid, address) {
if (this.checked = 'checked') {
$(productid).load(address);
}
else {
$(productid).load('http://www.divethegap.com/update/blank.html');
}
};
Problem is that the query to check if the box is checked or not does not work. If you check or uncheck the box it loads the address of the onclick event.
Any help would be appreciated but please keep in mind that the products are data driven so we cannot have specific IDs but rather IDs built of the Post ID.
Also when the page loads there will need to be some sort of global function which will work out what is 'checked' and load those URLs (products) in their specific DIVs.
Many Thanks,
Beware that you used = instead of == in the if() condition.
Also, have you tried with the :checked selector?
$("#id:checked")
JQuery documentation
function product_analysis(productid, address, box) {
if (box.checked) {
$(#productid).load(address);
}
else {
$(#productid).load('http://www.divethegap.com/update/blank.html');
}
};
and code for the box
onclick="product_analysis('#product_1231', 'http://www.divethegap.com/update/products/2010/11/padi-open-water/', this)"
I'm having trouble with some Javascript, and hopefully someone may be able to help!
First, here is the code:
function Client_Selected() {
var temp = $("input:radio[name='selected_client']:checked").val();
var f_input_name = "fname_" + temp;
var l_input_name = "lname_" + temp;
var first = $("input[name='"+f_input_name+"']").val();
var last = $("input[name='"+l_input_name+"']").val();
var content = first + " " + last;
var thispage = $("input[name='current_page']").val();
// Now Load the Notes!!!
dataString = 'web_id='+temp+'&Section='+thispage;
$.ajax({
type: "POST",
url: "<?=URL_SSL_WEBSITE_ROOT?>/notes/loadClientNotesAJAX",
data: dataString,
success: function(msg) {
$("#notes_body").html(msg);
$("#note_client_name").html(content);
}
});
$("#button_client_name").html(content);
$("#note_client_name").html(content);
$("input:radio[name=selected_client]:checked").attr(checked, true);
};
My problem is with the last line.
What's going on, is I have a list of clients who are associated with a radio button, when a button is clicked I make an AJAX call to get/display information about the client. If the last line is not present, then when I select a second client, it loads the information but the new client's radio button does not stay checked and instead the previous (or first) selected clients radio button remains checked.
With the last line I get an error of: "checked is undefined"
despite the error everything worked and the appropriate checkbox remained checked. However, with the new update to firefox yesterday ... the appropriate checkbox remains checked, though my success function never runs on the ajax call, and the javascript simply stops on the last line. It still works in IE, but I need to get this working again in firefox.
Any Ideas?
I've tried changing it to:
$("input:radio[name=selected_client]:checked").attr('checked', true);
Which then the success function runs, and the information is populated on my webpage, however I then get the problem of the newly selected checkbox NOT remaining checked and the previous one remains checked.
Any Help is much appreciated.
Thanks
.attr('checked','checked'); will check your checbox/radio box and .removeAttr('checked');
to uncheck it.
Looks like some quotes are missing
$("input:radio[name=selected_client]:checked").attr('checked', 'checked');
try the last line in the success function of the ajax call.
and use attr('checked',true)
checked is undefined
It certainly is. You used checked; JavaScript is looking for a variable called checked, which doesn't exist. You meant to say 'checked' with quotes, as a string.
However,
$("input:radio[name=selected_client]:checked").attr('checked', true);
Does nothing because you are checking a radio which by definition from your selector is already checked. What are you trying to do, here?
Note that if you are doing this in a radio button onclick handler, the :checked radio during the execution of the function will not be the newly-clicked one, it'll be the one that was previously checked. It is not until onclick event handling is finished that the click-to-change-checkedness actually goes through. If you want to find out the new radio during an onclick, you will have to look at this or the event object, depending on how you're calling the function.
Re other answers:
attr('checked','checked')
Can we please stop giving this out? It works, but not because of the reasons you think. jQuery attr() does not set HTML attributes (except in a couple of corner cases trying to work around browser bugs). It sets JavaScript properties, but trying to fix up the names to match the HTML attributes. So:
attr('checked', true);
or false for unsetting, is the correct approach. The value 'checked' only works because it is truthy when evaluated for a boolean property. Any non-empty string would do exactly the same.
If jQuery did set HTML attributes, attr('checked') would not work, because the HTML checked attribute corresponds to the initial setting of the checkbox (aka defaultChecked), not the current checkedness state.
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));
}