JQuery help with checkboxes and their values - php

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

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.

php : cannot see the hidden value submitted by Javascript

I'm pretty sure I'm missing something simple here, but it's driving me nuts !
This isn't the first form I'm using in PHP, but the first time submitting a hidden value.
When a menu item is clicked, I want to submit the page to itself - setting a simple parameter, so the php code does the processing.
The page gets submitted fine, but the hidden variable I set isn't available through _GET, _POST or _REQUEST. It should be _GET since that is what I've set as the method.
Here is the code if anyone can spot where I'm going wrong..
paramCustom is the one that I'm trying to set and work on.
The menu is a series of DIVs & anchors :
Option Xyz
The activateMenu javascript function is :
function activateMenu(optionTaken)
{
// Set the hidden variable
document.getElementById('paramCustom').value = optionTaken;
// Display it to confirm it is set correctly
var tt = document.getElementById('paramCustom').value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
The form is coded this way :
<form method="get" action="showProducts.php" id="linkSubmit">
<input type="hidden" id="paramCustom" name="paramCustom" />
<input type="submit" tabindex="-1" style="display:none;" />
</form>
In the php of the same page I'm trying to spit them out but all of them show blank !!
echo "paramCustom get is : ".$_GET['paramCustom']."<br/>"; // This should work
echo "paramCustom request is : ".$_REQUEST['paramCustom']."<br/>";
echo "paramCustom post is : ".$_POST['paramCustom']."<br/>";
OK, problem is that you are not actually stopping the event from firing. So clicking on the link, the function gets called, form submitted but you are not actually stopping the event in the onclick. So form submits but is immediately redirected to the href of the link cancelling the form submit. When the href is blank, it defaults back to the page you are currently on.
The way you are adding the onclick to the link (using an inline attribute) is like wrapping the event in a closure. So when onclick fires, what is really fired is more like function(){ activateMenu('option-xyz'); }. Your call to activateMenu is returning false, but the closure around it is not. You can just add return in front of activateMenu to have the event itself return false and cancel. Change the link like so:
Option Xyz
And then the actual event itself will return false, not just the function.
Here is a simple example to illustrate what is happening.
Doing a little change to the HTML you can set the inline event via Javascript, which is a way better:
<a id="xyz" href="#">Option Xyz</a>
And this is the Javascript edited for your purpose:
function activateMenu(optionTaken)
{
var paramCustom = document.getElementById('paramCustom');
// Set the hidden variable
paramCustom.value = optionTaken;
// Display it to confirm it is set correctly
var tt = paramCustom.value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
window.onload = (function() {
document.getElementById('xyz').onclick = function() {
activateMenu('option-xyz');
};
});
In PHP, as you know, $_GET gets the parameters of query string, $_POST of the POST data and $_REQUEST is a concat of the two arrays. In this case your method is GET so the value can be retrieved via _GET and _REQUEST, _POST is not going to work. Your code didn't worked to me probably because you had your function defined before DOM was loaded, so the event, when fired, probably throwed an exception.
This doesn't work because you haven't assigned a value. PHP won't recognize a field with a null value.
<input type="hidden" id="paramCustom" name="paramCustom" value="somevaluehere" />
[edit]
After testing this myself, it's because the onclick event is not behaving the way you anticipate. The easiest way to fix this is to use a HREF for you link. It's actually bad practice to rely solely on the onclick event anyway.
Option Xyz
This works perfectly.
The proper way to write an onclick looks like this:
Option Xyz
This works as well.
I've been using JQuery lately and it might be worth a shot.
Download the latest JQuery script and just link it to your page.
function activateMenu(optionTaken)
{
// Set the hidden variable
$("#paramCustom").val() = optionTaken;
// Display it to confirm it is set correctly
var tt = $("#paramCustom").val();
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
This isn't that much different than what you had but maybe JQuery will do a better job of assigning the value to your hidden field...
Cheers,
K

How to get an array of all checkboxes passed to the next page via _POST using JQuery

How to get an array of all checkboxes selected on the page, and then passing it to the next page (in this case php, so it can be picked up by php _POST function). I have come up with this :
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox:checked").each(function() {
selected.push($(this).val());
});
$('#od').submit(function() {
alert(this.selected); // *See note below
$.post('receiver.php', {'registration': selected});
return false;
});
});
</script>
But is does not seem to work :( It returns null, as if no checkboxes would have been added to the array, or maybe the post function is wrong. Can you point me in the right direction here?
I've found the following of issues:
You read the checked items on page load, thus ignoring all changes made by the user. Move that code to the submit() handler.
Your debugging code (alert(this.selected)) tries to display the value of the selected property for the form node. It isn't a reference to your JavaScript global variable selected. I suggest you use a proper debugging tool such as Firebug; alerts are highly unsuitable.
You sucessfully send the values of checked items. You just ignore the field name and rename everything to registration. That looks intended, otherwise report back:
{'registration': selected}
I suppose you can make jQuery serialize the values for you but fixing these little details in your code should do the trick anyway.
I think $("input:checkbox:checked") should be `$("input[type="checkbox"]:checked")
Or simply: $('input:checked', '#form-container');
$('#od').submit(function() {
var selected = $('input[type="checkbox"]:checked').toArray();
$.post('receiver.php', {'registration': selected});
return false;
});
The Data being posted might need to be split up.....

unknown checkbox problem

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

php jquery error in Firefox

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.

Categories