Mostly i have 28 items, i used pagination and display in 3pages using Ajax
each page have 10 items, whatever i selected in check box it should display values at bottom ,every thing is OK right now, but my problem is when i select items in second page the previous list is disappearing , when i return back to fist page it is not showing previously selected items .
iam not getting how to do this
please help
thanks
i used this jquery code to get checked values
function showValues() {
var page = $("#pagedis").val();
var fields = $(":input").serializeArray();
$("#results_" + page).empty();
jQuery.each(fields, function(i, field) {
$("#results_" + page).append(field.value + "<br> ");
});
}
i need the action like gmail if we select 3 items in one page ,4 items in 2nd page ,when i come back the checked value will never chage
do your checkboxes all have the same name? If not, name them all the same.
make sure each checkbox has a unique value attribute
attach a handler to keep track of the checkboxes checked in an array
:
// global variable somewhere
var checkedBoxes = new Array();
$('input[name=theNameYouDefinedAbove]').click(function(event){
checkedBoxes[$(this).val()] = $(this).is(':checked');
});
Now, when you paginate, just do this
:
$('input[name=theNameYouDefinedAbove]').each(function(index, checkbox){
if (checkedBoxes[$(checkbox).val()]) {
// NOTE: choose ONLY ONE!
// for jQuery 1.6+
$(checkbox).prop('checked', true);
// for all jQuery
$(checkbox).attr('checked', 'checked');
}
});
Related
To start off, sorry if this is a duplicate, or explained already. I've read a minimum of 15 other topics that I assumed are similar to mine, yet I haven't had any success in getting it to work.
I currently have a form that is action="submit.php". The form is an order form (see Jfiddle link at bottom of post). Inside submit.php I'm making an array of all $_POST values. That works great. Now the problem:
On the forum page (where user inputs), I have the following JQuery script that calculates totals. There are 3 types of totals (all this is clear in the JFiddle). The 3rd total, called "overallTotal", takes the sum of all "grandTotal"s and as of now, puts in #overallTotal ID. I need that number to be included in the form submission (i.e., so it is accessible by $_POST).
Thanks in advance, and sorry again if this is repetitive.
JSFiddle: http://jsfiddle.net/rc694dzL/
function oninput(e) {
// process this row first
var row = $(e.target).closest("tr");
// explicitly cast to a number
var quantity = +$(e.target).val();
var price = +row.find(".val1").text();
var output = row.find(".multTotal");
var total = price * quantity;
output.text(total);
// now calculate total
var subtotal = 0;
var table = $(e.delegateTarget);
table.find(".multTotal").each(function () {
subtotal += (+$(this).text());
});
table.find(".grandTotal").text(subtotal);
// now calculate overall total
var overallTotal = 0;
$(document).find(".grandTotal").each(function () {
overallTotal += (+$(this).text());
});
$('#overallTotal').text(overallTotal);
Add a hidden input in your form like this
<input type="hidden" name="overallTotal" id="overallTotalInput">
and set the value from javascript like this
$('#overallTotalInput').val(overallTotal);
Now when submitting the form, the value will be stored into $_POST['overallTotal']
Add some hidden fields in the form, and then populate the values with jquery.
Edit: tweaking your Fiddle now with an example: http://jsfiddle.net/dozecnp6/1/
1) Added the hidden input in the form:
<input type="hidden" name="OverallTotal" id="overallTotalField">
2) Added a bit to your oninput() function:
$('#overallTotalField').val(overallTotal);
in this fiddle i can use type="text" you can change it to type="hidden"
check this
fiddle
I'm hoping I'm on the right track here....
I have some elements on my page (tables).. that are dynamically generated based on the results of querying a DB.... (I add inside of a container DIV)..
inside these tables are some text..and a handful of checkboxes... each table is the same (outside of the value of the text fields)..
When a user clicks on a checkbox.. I add an element to another container DIV off to the side.
If a user un-checks the checkbox.. it removes the element from the container DIV on the side. On each 'click' event..... I am also either adding or removing the 'selections' from an ARRAY (and also updating this array to my PHP SESSION)..
When the user is done.. they click a button and go to another page.. where this SESSION array is grabbed and reviews/summarizes their 'choices'..
*there is no FORM tags.. checkboxes are free-form in the tables (not wrapped in any FORM tags..so there is NO general POST action to grab everything.. hence the use of an array/SESSION)
If the user goes BACK to the original 'selection page' (with the tables/checkboxes)..
I am re-populating the PAGE (both re-checking any checkboxes...and re-populating the elements in the container DIV to the side.. all based on the SESSION data)
In each checkbox.. I am adding a little PHP function to write in checked="checked" or not.. when the checkboxes instantiate)
like so:
<label><input id="articlesnaming" name="Articles Naming Expert" type="checkbox" value="0.00" <?=sessionCheck($row["id"] ."-A","Articles Naming Expert") ?> onclick=""/> Articles Naming Expert</label>
FYI: on the function being called:
function sessionCheck($recordID, $checkBoxID){
if(isset($_SESSION['userPicks']) && count($_SESSION['userPicks']) != 0){
for($r = 0; $r< count($_SESSION['userPicks']); $r++){
if($_SESSION['userPicks'][$r]['recordid'] == $recordID){
for($z=0; $z < count($_SESSION['userPicks'][$r]['itemsordered']); $z++){
if($_SESSION['userPicks'][$r]['itemsordered'][$z]['name'] == $checkBoxID){
return 'checked="checked"';
}else if($z == (count($_SESSION['userPicks'][$r]['itemsordered']) - 1)){
return "";
}
}
}else if($r == (count($_SESSION['userPicks']) - 1)){
return "";
}
}
}else{
return "";
}
}
Everything up to this point works fine...
Its when I go to dynamically build/add (append) those elements in the container DIV on the side... where problems happen.
I am getting them added just fine and when a user RE-VISITS the page.. previous checkboxes they had selected were/are checked again... -and-.. the elements ARE in the container DIV to the side of the stage/screen)...
PROBLEM: When I un-check one of the checkboxes, it DOES NOT remove the element in the container DIV on the side? I have to re-click the checkbox..(which adds a duplicate).. then I can un-check it.. but it only removes the NEW one..
Everything seems to work fine until a refresh/re-visit of the page (and I have to automatically populate the checkboxes and the elements in the container DIV on the side).. then the checkboxes stop behaving/interacting with the elements that were adding through another function (still same ID's...paths..from what I can tell)....and -not- added through an initial checkbox event/action..
I am grasping at straws here.... it is perhaps because I'm using a PHP function to set the checkboxes on refresh? and it maybe doesn't know its current state? (although the visual state of the checkbox is accurate/correct)
Any ideas are appreciated.
Code used to set/un-set checkboxes & add/remove elements from the side container DIV :
<script>
//var to hold current check box clicked
var targetCheckbox;
//var to hold cumulative total
var totalPrice = 0;
//array to keep track of user picks from returned record results
//try to get SESSION array (if available/set) from PHP into jQuery using json_encode()
<?php if(isset($_SESSION['userPicks'])){ ?>
//overwrite jQuery userPicks MAIN array
var userPicks = <?php echo json_encode($tempArray) ?>;
<? }else{ ?>
//create new jQuery userPicks MAIN array, and populate through user clicks/interaction
var userPicks = [];
<? } ?>
$(document).ready(function() {
//check to see if seesion and populate checks and side column from previous picks
//if existing session, loop through and populate the CHOICES column
if(userPicks.length > 0){
console.log("SESSION EXISTS, POPULATE CHOICES COLUMN FROM ARRAY");
for(i=0; i<userPicks.length; i++){
//build up sub array data first then append at one time.
var subArrayLength = userPicks[i].itemsordered.length;
var subArray = '';
for(s=0; s<subArrayLength; s++){
subArray += '<li id="' + userPicks[i].orderid + userPicks[i].checkboxid + '">' + userPicks[i].itemsordered[s].name + '</li>';
}
$("#choicesWrapper #itemList").append('<div class="recordChoices"><h5>CASE NAME: '+userPicks[i].casename+'</h5><ul id="'+userPicks[i].recordid+'">'+subArray+'</ul></div>');
}
}
//onClick event
$('.orderOptions').on('click', 'input:checkbox', function () {
//routine when checkbox is checked
if ($(this).is(":checked")) {
$(this).prop("checked", true);
console.log("checked");
//console.log('doesnt exist..create it');
$("#choicesWrapper #itemList").append('<div class="recordChoices"><h5>CASE NAME: '+caseName+'</h5><ul id="'+resultsID+'"><li id="'+orderID+targetCheckbox+'">'+itemOrdered+'</li></ul></div>');
}else{
$(this).prop("checked", false);
console.log("un-checked");
//remove the option from right column (li element)
console.log("REMOVE TARGET: #choicesWrapper #itemList #"+resultsID+" "+orderID+targetCheckbox);
$("#choicesWrapper #itemList #"+resultsID+" #"+orderID+targetCheckbox).remove();
//check if no more children and remove parent/title (record container/div)
if ($("#choicesWrapper #itemList #"+resultsID+" li").length > 0) {
//console.log("Still has children...do nothing");
}else{
//console.log("No Children...");
$("#choicesWrapper #itemList #"+resultsID).parent().remove();
}
}
}
}
</script>
Oddly enough, when things are 'auto-populated' from the SESSION data (like on refresh or re-visiting the page) and when things 'break', unchecking the checkboxes doesn't remove things, but when I uncheck the very last checkbox in a group, it does remove the parent (so that parent removal code/routine is being executed...but not then child )
I'm thinking this is a pathing issue? (I believe I am creating things with exactly the same ID's/classes...etc).
Definitely worth the +1 if you answer! :)
The only other thing I can think of is.. HOW the userPicks array gets created.. initial visit to page, I just create an empty JS/jQuery array and wait to push/populate it when a user clicks a checkbox (code above for onClick stuff).
But when a user visits the page (refresh or re-visit) and -HAS- (previous) SESSION data still available.... then I grab the PHP SESSION array.. and pass it to jQuery using json_encode()...
Do I need to add/delete from that array differently than I do if I created normally?
On php page in a form, one combo-box has list of customers from a MySQL table customer. Another combo-box contains invoiceno fields from the invoice table, respective to customer records.
I want to select a customer from the first combo box and filter invoiceno from the second one according to the customer. Can anyone help me accomplish this?
For example, if I select customer1, the second combo box should show all invoiceno respective to the customer1. I want to do this without refreshing, reloading, or POSTing the page. If I get the first selection in a php variable $customer, it's enough for me. Thanks!
AJAX is your friend:
Capture onchange event of the first combo box
Then send the value of the selected item via AJAX to your PHP script
Your PHP script loads the corresponding values from the databases and returns them (for example in JSON format)
And finally you display/insert the returned data via JavaScript.
Pseudo code:
JavaScript:
function displayData(json)
{
// Do something
}
document.getElementById("your-combobox").addEventListener("change", function()
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState==4 && xhr.status==200)
{
displayData( JSON.parse(xhr.responseText) ); // Call displayData with the JSON
}
};
xhr.open("GET", "your-script.php?combobox1="+encodeURIComponent(this.value));
xhr.send(null); // Send AJAX request
});
PHP:
<?php
if (!isset($_GET['combobox1'])) exit('{}');
$data = GetDataFromDB_AsArray();
echo json_encode($data);
?>
First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.
What I'm trying to do is use jQuery to grab any checkboxes that are checked on the page. The boxes are dynamically created using a specific ID number of each one for the ID and Value.
What is the easiest way about getting it to grab the values of each checked item? Then check if less than or greater than 3 is checked. If only 3 are checked then send the values of each checkbox to my php script. I'm using a regular button on the page so I will proably have to use the .click method since its not actually part of a form to submit.
I've seen several examples around here but not quite what I'm trying to do.
$('#mybtn').live('click',function(){
$("input[type=checkbox]").each(function() {
// I guess do something here.
)};
)};
the code i believe you are wanting is this
$('#mybtn').live('click',function(){
var num_checked = $("input[type=checkbox]:checked").length;
var checkbox_values = new Array();
if( num_checked > 3 ) {
//its greater than 3
//do what you need to do
} else if( num_checked < 3 ) {
//its less than 3
//do what you need to do
}else {
//it equals 3
//do what you need to do
//go thru and add values to array
$("input[type=checkbox]:checked").each(function() {
checkbox_values.push($(this).val());
});
}
});
if you want to send email of variables you can output array checkbox_values to php
If all your checkboxes are in a form, you can do $('#form_id').serialize();
You can get how many are checked using
$("input[type=checkbox]:checked").length
http://jsfiddle.net/XKRRL/7/
Not really sure what you want to do with the ones that are checked, but the js fiddle loops through the checked ones. From there you could grab id's etc.
full code
$(function() {
$('#mybtn').live('click', function() {
var checkedBoxes = $("input[type=checkbox]:checked"),
checkedNum = checkedBoxes.length;
if(checkedNum === 3){
for(var i=0; i< checkedNum; i++){
alert($(checkedBoxes).eq(i).val());
}
}
});
});
It's simple to grab all checked checkboxes:
var checked = $('input[type=checkbox]:checked'),
count = checked.length;
if (count == 3) {
values = $.map(checked, function(i){
return $(this).val();
});
}
Then do whatever you want on the values array.