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.
Related
I'm using Codeigniter and wants to know how I can make a checkbox that submits the form on click?
Secondly, this checkbox will be one of several checkboxes that will act as a filter like products > $20, products < $30, how do i pass it in the url? I'm thinking /1+2+3
Haven't worked with Codeigniter much, but I can answer how to make the form submit on checking the checkbox with JS:
<form id="something">
<input type="checkbox" name="foo" id="foo" value="yes" />
</form>
<script type="text/javascript">
$("#foo").click(function() {
if ($(this).is(":checked"))
$("#something").submit();
});
</script>
The javascript questions seem to have been solved already; let's step to the codeigniter ones.
You can pass the url in one of those two ways.
Idiomatic but limited: as /1/2/3/4/etc. The controller function handling that url could both use func_get_args to read them or, if you already know how many parameters will be passed at the most, give a default value of null to all non-necessary paramenters;
Not Codeigniterish but seriously better for search parameters: enable the query strings on your config file, pass arguments as you would normally with GET (min=2&max=3 and so on) and get their value with CI's input class ($min = $this->input->get('min')).
This has nothing to do with PHP, nor CodeIgniter. The solution is to submit the form in the onclick event of the element.
<input type="checkbox" name="filterx" onclick="document.forms[0].submit()" />
You can use the OnSubmit event of the form to nicely format the url, if you like.
To do this, you can
get the values of all desired elements,
build a nice url from it,
set the url using location.href = yourniceurl,
cancel the regular submit by returning false.
Note that both solutions require javascript to be enabled. So it is a good thing to have other means of submitting the form (submit button). Don't rely on submitting by pressing Enter. Opera will use the Enter key for toggling the checkbox instead of submitting the form.
If you like, you can hide the submit button using Javascript, that way, users having Javascript will have their form auto-submitted, while users without can use the button.
You will need to make sure that your server side form validator not only accepts the nice url, but the ugly url (which posts values like ?filterx=on) too.
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);
}
Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.
I need to get values from some selected checkboxes and pass those values through pagination in php/mysql. If on another page user selects other checkboxes, I need to add their values to array selected earlier.
I need this for a product comparison page. In short I need to:
get the checkbox values
store them
include the checkbox values from other pages in pagination
and when user selects "compare" send that array to compare page.
Anybody know how to do this? Related examples would be appreciated?
There are different ways to maintain state across pages, including cookies, session variables, hidden inputs, passing them in the querystring, persisting to database, etc. In this case I would probably use a session variable.
For more info on PHP session see PHP Sessions.
One solution would be to load all of the pages at once in their own divs inside of a form. When you click on a new page link, hide all divs except the one you need to show. That way all checkboxes are submitted in the same form, making it easier to handle server-side. That of course depends on how heavy each individual page is and how many pages there are.
Another solution would be to keep a session variable, tracking what was clicked. Each time someone clicks to go to another page. POST to the server a list of the checkboxes.
You could do it by using javascript to store the checkbox selection in a cookie. Here's some sample code to get you going in the right direction.
var aa_checkbox;
function init_checkbox(){
//setup blank cb cookie
if(!Cookie.read('cb')){
Cookie.write('cb', JSON.encode({}));
}
//setup "associative array" to match what is currently in the cookie
aa_checkbox = JSON.decode(Cookie.read('cb'));
//set up each checkbox with class="remember_cb"
$$('input.remember_cb').each(function(el){
//mark checked if it is in the cookie
if(aa_checkbox[el.name]){
el.checked = 'checked'
}
//setup onclick event to put checkbox status in the
el.addEvent('click', function(){
if(el.checked){
aa_checkbox[el.name] = 1;
}else{
delete(aa_checkbox[el.name]);
}
})
})
//save aa_checkbox back into cookie upon leaving a page
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};
setup_form();
return true;
}
function setup_form(){
//set up form so that it adds the inputs upon submit.
$$('form.remember_cb_form').each(function(form){
form.addEvent('submit', function(ev){
//clean up previously inserted inputs
var aa_hidden_insert = $$('input.hidden_insert');
$each(aa_hidden_insert, function(el){
el.parentNode.removeChild(el);
})
var el_form = this;
//insert hidden elements representing the values stored in aa_checkbox
$each(aa_checkbox, function(i_value, s_name){
if(i_value){
var el_input = document.createElement('input');
el_input.type = 'hidden';
el_input.value = i_value;
el_input.name = s_name;
el_input.setAttribute('class', 'hidden_insert');
el_form.appendChild(el_input);
}
});
});
});
}
window.addEvent('domready', init_checkbox);
There is a working demo here and a more thorough explanation here
Your pagination links could actually perform a form POST, then read the checkbox[] in ur php script, and update a hidden form element or add the value to a session, anything stateful. so your anchor could look something like
<a href="#" onclick="document.myform.submit()">next</a>
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));
}