Add ajax level pagination with tablesorter jquery plugin pager - php

I have a table in which I want to implement server side pagination.
Currently what I am doing is I am fetching entire data in one go (40-50k records) and assigning it to an array ($batchesData) and I have implemented a pager plugin of the jquery table sorter on it which is technically wrong because it slows down the system.
I want to implement server side pagination wherein only 10 records per page are fetched and displayed with this library but need some leads on how to proceed
This is how my tpl file looks like
<table class="table table-striped projects tablesorter"
id="batchTable" style="font-size: 13px;">
<th>
.....
.....
</th>
<tbody>
{if !empty($batchesData)}
{foreach from = $batchesData key = filter item = value}
<tr>
......
......
</tr>
{/foreach}
</tbody>
</table>
Pager code
<div style = "margin-left:30%" id="pager" class="tablesorterPager" >
<form>
<img src="/assets/images/first.png" width = "5%" height = "auto" class="first"/>
<img src="/assets/images/previous.png" width = "5%" height = "auto" class="prev"/>
<input type="text" class="pagedisplay"/>
<img src="/assets/images/next.png" width = "5%" height = "auto" class="next"/>
<img src="/assets/images/last.png" width = "5%" height = "auto" class="last"/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="5">5 per page</option>
<option value="50">50 per page</option>
<option value="100">100 per page</option>
</select>
</form>
</div>
Js Code
/**
* To sort table columns in asc/desc order in Batch Listing View
*/
$('#batchTable')
.tablesorter({widthFixed: true, widgets: ['zebra']}) ;
/**
* To apply pagination in Batch Listing View
*/
$('#batchTable')
.tablesorterPager({container: $("#pager")});
Any leads would be highly appreciated
pager.js
(function($) {
$.extend({
tablesorterPager: new function() {
function updatePageDisplay(c) {
var s = $(c.cssPageDisplay,c.container).val((c.page+1) + c.seperator + c.totalPages);
}
function setPageSize(table,size) {
var c = table.config;
c.size = size;
c.totalPages = Math.ceil(c.totalRows / c.size);
c.pagerPositionSet = false;
moveToPage(table);
fixPosition(table);
}
function fixPosition(table) {
var c = table.config;
if(!c.pagerPositionSet && c.positionFixed) {
var c = table.config, o = $(table);
if(o.offset) {
c.container.css({
position: 'realtive'
});
}
c.pagerPositionSet = true;
}
}
function moveToFirstPage(table) {
var c = table.config;
c.page = 0;
moveToPage(table);
}
function moveToLastPage(table) {
var c = table.config;
c.page = (c.totalPages-1);
moveToPage(table);
}
function moveToNextPage(table) {
var c = table.config;
c.page++;
if(c.page >= (c.totalPages-1)) {
c.page = (c.totalPages-1);
}
moveToPage(table);
}
function moveToPrevPage(table) {
var c = table.config;
c.page--;
if(c.page <= 0) {
c.page = 0;
}
moveToPage(table);
}
function moveToPage(table) {
var c = table.config;
if(c.page < 0 || c.page > (c.totalPages-1)) {
c.page = 0;
}
renderTable(table,c.rowsCopy);
}
function renderTable(table,rows) {
var c = table.config;
var l = rows.length;
var s = (c.page * c.size);
var e = (s + c.size);
if(e > rows.length ) {
e = rows.length;
}
var tableBody = $(table.tBodies[0]);
// clear the table body
$.tablesorter.clearTableBody(table);
for(var i = s; i < e; i++) {
//tableBody.append(rows[i]);
var o = rows[i];
var l = o.length;
for(var j=0; j < l; j++) {
tableBody[0].appendChild(o[j]);
}
}
fixPosition(table,tableBody);
$(table).trigger("applyWidgets");
if( c.page >= c.totalPages ) {
moveToLastPage(table);
}
updatePageDisplay(c);
}
this.appender = function(table,rows) {
var c = table.config;
c.rowsCopy = rows;
c.totalRows = rows.length;
c.totalPages = Math.ceil(c.totalRows / c.size);
renderTable(table,rows);
};
this.defaults = {
size: 10,
offset: 0,
page: 0,
totalRows: 0,
totalPages: 0,
container: null,
cssNext: '.next',
cssPrev: '.prev',
cssFirst: '.first',
cssLast: '.last',
cssPageDisplay: '.pagedisplay',
cssPageSize: '.pagesize',
seperator: "/",
positionFixed: true,
appender: this.appender
};
this.construct = function(settings) {
return this.each(function() {
config = $.extend(this.config, $.tablesorterPager.defaults, settings);
var table = this, pager = config.container;
$(this).trigger("appendCache");
config.size = parseInt($(".pagesize",pager).val());
$(config.cssFirst,pager).click(function() {
moveToFirstPage(table);
return false;
});
$(config.cssNext,pager).click(function() {
moveToNextPage(table);
return false;
});
$(config.cssPrev,pager).click(function() {
moveToPrevPage(table);
return false;
});
$(config.cssLast,pager).click(function() {
moveToLastPage(table);
return false;
});
$(config.cssPageSize,pager).change(function() {
setPageSize(table,parseInt($(this).val()));
return false;
});
});
};
}
});
// extend plugin scope
$.fn.extend({
tablesorterPager: $.tablesorterPager.construct
});
})(jQuery);
Library Used - http://tablesorter.com/docs/
http://tablesorter.com/docs/example-pager.html

Related

the script (Tagging with multi-value select boxes) cant show when edit

I'm using this feature https://select2.org/tagging#tagging-with-multi-value-select-boxes
(Tagging with multi-value select boxes) in view
the index can be used properly as in the picture
but when i edit the feature it can't (Tagging with multi-value select boxes) in edit
please help me to solve this.
this my blade
#elseif($dataform['type']=='multiple_advance')
<div class="col-sm-{{$dataform['col'] ?? 12}}">
<label class="form-label"><b>{{$dataform['label']}}</b></label>
<div class="form-group">
<select name="{{$dataform['field']}}" id="{{$dataform['field']}}" multiple="multiple" class="form-control {{$dataform['field']}}">
<option value="">{{$dataform['default']}}</option>
#foreach($dataform['combodata'] as $key => $combodata)
<option value="{{$combodata['comboValue']}}">{{$combodata['comboLabel']}}</option>
#endforeach
</select>
<small class="form-text text-muted">{{$dataform['keterangan']}}</small>
<script>
$(".{{$dataform['field']}}").select2({
placeholder: "{{$dataform['default']}}",
tags: true
});
</script>
</div>
</div>
this is my javascript
function grid_edit(id, primaryKey) {
var data = document.getElementById('alldata').value;
var dataobj = JSON.parse(data).data;
for (var i = 0; i < dataobj.length; i++) {
var a = 'dataobj[i].' + primaryKey.id;
// console.log(a);
if (eval(a) == id) {
var field = document.getElementById('formAllField').value;
var fieldobj = JSON.parse(field);
//masukkan PK dulu
document.getElementById(primaryKey.id).value = id;
//masukkan field yang lain
for (var j = 0; j < fieldobj.length; j++) {
var b = 'dataobj[i].' + fieldobj[j].field;
if (fieldobj[j].type != 'password') {
if (fieldobj[j].type == 'combo') {
$("#" + fieldobj[j].field).val(eval(b)).find(':selected').trigger('change');
} else if (fieldobj[j].type == 'autocomplete') {
setAutocompleteVal(fieldobj[j].url, eval(b), fieldobj[j].text, fieldobj[j].field);
} else if (fieldobj[j].type == 'image') {
// document.getElementById(fieldobj[j].field).value = String(eval(b));
} else if (fieldobj[j].type == 'summernote_advance') {
$('#' + fieldobj[j].field).summernote("code", eval(b));
// console.log(eval(b));
} else if (fieldobj[j].type == 'multiple') {
//set value from multiple select
var multiple = eval(b).split(',');
$("#" + fieldobj[j].field).select2().val(multiple).trigger('change');
} else if (fieldobj[j].type == 'multiple_advance') {
//set value from multiple select
var multiple = eval(b).split(',');
console.log(multiple);
$("#" + fieldobj[j].field).select2().val(multiple).trigger('change');
} else {
document.getElementById(fieldobj[j].field).value = eval(b);
}
}
}
}
}
}

Implement a dynamic selectbox in html

I am trying to develop a select box so that I can change the selected option dynamically
e.g.
selectbox option display message
---------------------------------------------
field 1 text
field 2 integer
field 3 bool
There are three select boxes. The first select box provide three options.
when select box 1 is selected, the other select boxes will have only 2 options (excluding the selected one)
When select box 2 is selected, the other select boxes will have only 1 option (excluding the selected two)
When a select box's value changes, the appropriate message is displayed.
All of the text that will be displayed is read in from a database as an array in the following format:
name text
id integer
address text
Then I create a select box with the three option
When I set select box 1's value as name, the text message is displayed, and so on.
How should I implement this? (I hope you get my idea) Thank you again for your help.
Thank you
I'd suggest something akin to the following:
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset');
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};​
JS Fiddle demo.
Edited to add the messages, as requested in comments (which I overlooked in the actual question...):
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset'),
msgs = ['text','integer','boolean'];
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
hideMessage(elem);
};
function displayMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = msgs[i];
span.style.display = 'block';
}
}
};
function hideMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = '';
span.style.display = 'none';
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
sel1.onfocus = function() {
displayMessage(this);
};
sel2.onfocus = function() {
displayMessage(this);
};
sel3.onfocus = function() {
displayMessage(this);
};
sel1.onblur = function() {
hideMessage(this);
sel2.onblur = function() {
hideMessage(this);
};};
sel3.onblur = function() {
hideMessage(this);
};​​
JS Fiddle demo.
Take a look at this plugin, maybe it can help you.
For the data than you can put a php foreach for the <option> element on the select.

How to get total value on dynamic value?

I have form like this :
<input type='hidden' name='seq' id='idseq' value='1' />
<div id='add_field' class='locbutton'><a href='#' title='Add'>Add</a></div>
<div id='remove_field' class='locbutton2'><a href='#' title='Delete'>Delete</a></div>
<div id="idcover">
1.<br />
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]'
disabled></div>
</div>
</div>
<br /><br />
<div id='idtotalcover' class='totalcover'>
Total <div class='total'><input type='text' name='total' id='idtotal' disabled /></div>
</div>
This is the jquery script:
<script type="text/javascript">
$(document).ready(
function ()
{
$("input[id^=score],input[id^=weight]").bind("keyup", recalc);
recalc();
var counter = $("#idseq").val();
$("#add_field").click(function ()
{
counter++;
$.ajax({
url: 'addinput.php',
dataType: "html",
data: "count="+counter,
success: function(data)
{
$('#idcover').append(data);
$('.dua input').keyup(function()
{
var $duaInput = $(this);
var weight=$duaInput.val();
var score=$duaInput.closest(".group").find('.satu input').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$duaInput.closest(".group").find('.tiga input').val(data);
}//success
});//ajax
});
}//success
});//ajax
});
});
function recalc()
{
var a=$("input[id^=score]");
var b=$("input[id^=weight]");
$("[id^=weightscore]").calc("(score * weight)/100",{score: a,weight: b},
function (s)
{
return s.toFixed(2);
},
function ($this){
//function($("[id^=weightscore]")){
// sum the total of the $("[id^=total_item]") selector
//alert($this);
//var sum = $this.sum();
var sum=$this.sum();
$("#idtotal").val(sum.toFixed(2));
}
);
}
</script>
This is the php code:
<?
$count=$_GET['count'];
echo"
<br>
$count
<div class='group' >
<div class='satu'>
<input type='text' name='score[$count][]' id='score[$count][]'>
</div>
<div class='dua'>
<input type='text' name='weight[$count][]' id='weight[$count][]'> %
</div>
<div class='tiga'>
<input type='text' name='weightscore[$count][]' id='weightscore[$count][]' disabled>
</div>
</div>";
?>
When I click the Add button, i cant get value on new form so that the new form cannot be calculated. What can i do to get total value on dynamic value ?
I remember reading this exact same question yesterday and I still have no idea of what you're trying to do.
Why are you adding inputs through AJAX instead of creating them in Javascript from the beginning? AJAX calls are expensive and are recommended to be used when you need to update/retrieve values from the server.
Why are you trying to do your calculations on the server side anyway? If you're dealing with dynamic input, you should be doing the calculations client side, then update the server when you're done.
Why do you use obscure name/id attribute values?
Anyway,
I created this example, it contains two different solutions, one with a ul and a table. Hopefully, the example matches what you're trying to do and might give you some insight.
I use a timer to update simulated server data. The timer is set to the variable update_wait. The other dynamic calculations are done client side.
I'll post the Javascript code as well, in case you don't like to fiddle
Example | Javascript
var update_server_timer = null,
update_wait = 1000; //ms
var decimals = 3;
/**********************
List solution
**********************/
function CreateListRow(){
var eLi = document.createElement("li"),
eScore = document.createElement("div"),
eWeight = document.createElement("div"),
eWeightScore = document.createElement("div");
var next_id = $("#cover li:not(.total)").length + 1
eScore.className = "score";
eWeight.className = "weight";
eWeightScore.className = "weightscore";
//Score element
var eScoreInput = document.createElement("input");
eScoreInput.type = "text";
eScoreInput.name = "score_"+next_id;
eScoreInput.id = "score_"+next_id;
eScore.appendChild(eScoreInput);
//Weight element
var eWeightInput = document.createElement("input");
eWeightInput.type = "text";
eWeightInput.name = "weight_"+next_id;
eWeightInput.id = "weight_"+next_id;
var eWeightPerc = document.createElement("div");
eWeightPerc.className = "extra";
eWeightPerc.innerHTML = "%";
eWeight.appendChild(eWeightInput);
eWeight.appendChild(eWeightPerc);
//Weightscore element
var eWeightScoreInput = document.createElement("input");
eWeightScoreInput.type = "text";
eWeightScoreInput.name = "weight_"+next_id;
eWeightScoreInput.id = "weight_"+next_id;
eWeightScore.appendChild(eWeightScoreInput);
$(eScore).keyup(function(){
CalculateListRow($(this).closest("li"));
});
$(eWeight).keyup(function(){
CalculateListRow($(this).closest("li"));
});
//item element
eLi.appendChild(eScore);
eLi.appendChild(eWeight);
eLi.appendChild(eWeightScore);
return eLi;
}
function CalculateListRowTotal(){
var fTotal = 0;
$("#cover li:not(.total) div:nth-child(3) input").each(function(){
var fVal = parseFloat($(this).val());
if(isNaN(fVal)) fVal = 0;
fTotal += fVal;
});
fTotal = parseFloat(fTotal.toFixed(decimals));
$("#cover li.total div input").val(fTotal);
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateListRow($Li){
var fScore = parseFloat($("div.score input", $Li).val()),
fWeight = parseFloat($("div.weight input", $Li).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("div.weightscore input", $Li).val(parseFloat(fRes.toFixed(decimals)));
CalculateListRowTotal();
}
$("#cover li div.weight input, #cover li div.score input").keyup(function(){
CalculateListRow($(this).closest("li"));
});
function AddListRow(){
$("#cover li.total").before(CreateListRow());
RestartUpdateServerTimer();
}
function RemoveListRow(){
$("#cover li.total").prev().remove();
CalculateListRowTotal();
}
$(".left_container .menu .add").click(function(){ AddListRow(); });
$(".left_container .menu .rem").click(function(){ RemoveListRow(); });
/**********************
Table solution
**********************/
function CreateTableRow(){
var eTr = document.createElement("tr"),
eTds = [document.createElement("td"),
document.createElement("td"),
document.createElement("td")];
var next_id = $("#cover2 tbody tr").length + 1;
$(eTds[0]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "score_"+next_id;
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eInput;
});
$(eTds[1]).append(function(){
var eRelativeFix = document.createElement("div"),
eInput = document.createElement("input"),
eExtra = document.createElement("div");
eRelativeFix.className = "relative_fix";
eInput.type = "text";
eInput.name = eInput.id = "weight_"+next_id;
eExtra.innerHTML = "%";
eExtra.className = "extra";
eRelativeFix.appendChild(eInput);
eRelativeFix.appendChild(eExtra);
$(eInput).keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
return eRelativeFix;
});
$(eTds[2]).append(function(){
var eInput = document.createElement("input");
eInput.type = "text";
eInput.name = eInput.id = "weightscore_"+next_id;
return eInput;
});
for(i = 0; i < eTds.length; i++){
eTr.appendChild(eTds[i]);
}
return eTr;
}
function CalculateTableRowTotals(){
var $rows = $("#cover2 tbody tr"),
$totals = $("#cover2 tfoot tr th");
var fTotal = [];
//Each row
$rows.each(function(){
var $columns = $("td", this);
//Each column
$columns.each(function(i, e){
var fVal = parseFloat($("input", e).val());
if(isNaN(fVal)) fVal = 0;
if(isNaN(fTotal[i])) fTotal[i] = 0;
fTotal[i] += fVal;
});
});
for(i = 0; i < fTotal.length; i++){
fTotal[i] = parseFloat(fTotal[i].toFixed(decimals));
}
fTotal[1] = (fTotal[2]/fTotal[0]*100).toFixed(decimals)+"%";
fTotal[2] = parseFloat(fTotal[2].toFixed(decimals));
$totals.each(function(i, e){
$(this).text(fTotal[i]);
});
//Update server variables here
RestartUpdateServerTimer();
}
function CalculateTableRow($Tr){
var fScore = parseFloat($("td:nth-child(1) input", $Tr).val()),
fWeight = parseFloat($("td:nth-child(2) input", $Tr).val())/100,
fRes = (fScore*fWeight);
if(isNaN(fRes)) fRes = 0.00;
$("td:nth-child(3) input", $Tr).val(parseFloat(fRes.toFixed(decimals)));
CalculateTableRowTotals();
}
function AddTableRow(){
if($("#cover2 tbody tr").length == 0){
$("#cover2 tbody").append(CreateTableRow());
}else{
$("#cover2 tbody tr:last-child").after(CreateTableRow());
}
RestartUpdateServerTimer();
}
function RemoveTableRow(){
$("#cover2 tbody tr:last-child").remove();
CalculateTableRowTotals();
}
$(".right_container .menu .add").click(function(){ AddTableRow(); });
$(".right_container .menu .rem").click(function(){ RemoveTableRow(); });
$("#cover2 tbody tr td:nth-child(1) input, #cover2 tbody tr td:nth-child(2) input").keyup(function(){
CalculateTableRow($(this).closest("tr"));
});
/**********************
Server data
- Simulates the data on the server,
- whether it be in a SQL server or session data
**********************/
var ServerData = {
List: {
Count: 3,
Total: 5.50
},
Table: {
Count: 3,
Totals: [65, 8.46, 5.50]
}
};
function UpdateServerData(){
//List
var ListCount = $("#cover li:not(.total)").length,
ListTotal = $("#cover li.total input").val();
//Table
var TableCount = $("#cover2 tbody tr").length,
TableTotals = [];
$("#cover2 tfoot th").each(function(i, e){
TableTotals[i] = parseFloat($(this).text());
});
var data = {
json: JSON.stringify({
List: {
Count: ListCount,
Total: ListTotal
},
Table: {
Count: TableCount,
Totals: TableTotals
}
})
}
//Update
$.ajax({
url: "/echo/json/",
data: data,
dataType: "json",
type:"POST",
success: function(response){
ServerData.List = response.List;
ServerData.Table = response.Table;
var displist = "Server data<h1>List</h1><ul><li>Count: "+ServerData.List.Count+"</li><li>Total: "+ServerData.List.Total+"</li></ul>",
disptable = "<h1>Table</h1><ul><li>Count: "+ServerData.Table.Count+"</li>";
for(i=0; i<ServerData.Table.Totals.length; i++)
disptable += "<li>Total "+i+": "+ServerData.Table.Totals[i]+"</li>";
disptable += "</ul>";
$("#server_data").html(displist+"<br />"+disptable).effect("highlight");
}
});
}
function RestartUpdateServerTimer(){
if(update_server_timer != null) clearTimeout(update_server_timer);
update_server_timer = setTimeout(function(){
UpdateServerData()
}, update_wait);
}
UpdateServerData();
Update
Since you have a hard time grasping the concept, here's a copy paste solution that will work for you without having to use AJAX. I would like to point out that your HTML markup and general coding is a total mess...
Example | Code
<script type="text/javascript">
$(document).ready(function(){
function CreateInput(){
var $group = $("<div>"),
$score = $("<div>"),
$weight = $("<div>"),
$weightscore = $("<div>");
var group_count = $("div.group").length+1;
$group.addClass("group");
$score.addClass("satu");
$weight.addClass("dua");
$weightscore.addClass("tiga");
var $input_score = $("<input>"),
$input_weight = $("<input>"),
$input_weightscore = $("<input>")
$input_score
.attr("name", "score["+group_count+"][]")
.attr("type", "text")
.attr("id", "score["+group_count+"][]");
$input_weight
.attr("name", "weight["+group_count+"][]")
.attr("type", "text")
.attr("id", "weight["+group_count+"][]");
$input_weightscore
.attr("name", "weightscore["+group_count+"][]")
.attr("type", "text")
.attr("id", "weightscore["+group_count+"][]")
.attr("disabled", true);
$input_score.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$input_weight.keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$score.append($input_score);
$weight.append($input_weight);
$weightscore.append($input_weightscore);
$group.append($score)
.append($weight)
.append($weightscore);
return $group;
}
function CalculateGroup($group){
var fScore = parseFloat($(".satu input", $group).val()),
fWeight = parseFloat($(".dua input", $group).val()),
fWeightScore = parseFloat((fScore*(fWeight/100)).toFixed(2));
if(isNaN(fWeightScore)) fWeightScore = 0;
$(".tiga input", $group).val(fWeightScore);
CalculateTotal();
}
function CalculateTotal(){
var fWeightScoreTotal = 0;
$("#idcover div.group div.tiga input").each(function(){
var fTotal = parseFloat(parseFloat($(this).val()).toFixed(2));
if(isNaN(fTotal)) fTotal = 0;
fWeightScoreTotal += fTotal;
});
fWeightScoreTotal = parseFloat(fWeightScoreTotal.toFixed(2));
$("#idtotalcover div.total input").val(fWeightScoreTotal);
}
$(".satu input, .dua input").keyup(function(){
CalculateGroup($(this).parents(".group"));
});
$("#add_field a").click(function(e){
$("#idcover").append(CreateInput());
e.preventDefault();
});
$("#remove_field a").click(function(e){
$("#idcover div.group:last-child").remove();
CalculateTotal();
e.preventDefault();
});
});
</script>

undefined value single checkbox javascript to another page

i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltbody>
&lta href="addevent.php" rel="facebox" &gtlink&lt/a&gt
&lt/body>
addevent.php
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltscript language="javascript" type="text/javascript"&gt
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i&ltelemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i &lt len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i&ltformNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i &lt max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
&lt/script&gt
&ltscript type="text/javascript"&gt
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i &lt lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") &gt -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j &lt labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
&lt/script&gt
&lt/head&gt
&ltform name="eventAgendaForm" id="eventAgendaForm" &gt
&ltul class="checklist cl3"&gt
&ltli &gt&ltlabel for="c1"&gt
&ltinput id="checkId" name="checkName" value="1" type="checkbox" &gt
&lt/label&gt&lt/li&gt&lt/ul&gt
&ltinput class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" /&gt
&lt/form&gt
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.

shuffle slider display

i have a problem on the slider of my site, though the slider works fine and good but i need it to be random or shuffle instead of displaying an ordered content..
i already have the code and it need some modification.
this is the line on the main file.php
<script type="text/javascript">
$(document).ready(function() {
$('#slider1').s3Slider({
timeOut: 8000
});
});
<div id="slider1">
<ul id="slider1Content">
<li class="slider1Image">
<img src="products/1.png" alt="1" />
<span class="left">
caption1
</span>
</li>
<li class="slider1Image">
<img src="products/2.png" alt="2" />
<span class="right">caption2
</span>
</li>
<li class="slider1Image">
<img src="products/3.png" alt="3" />
<span class="right">caption3.
</span>
</li></div>
this is the java script file
(function($){
$.fn.s3Slider = function(vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#" + element[0].id + "Content ." + element[0].id + "Image");
var itemsSpan = $("#" + element[0].id + "Content ." + element[0].id + "Image span");
items.each(function(i) {
$(items[i]).mouseover(function() {
mOver = true;
});
$(items[i]).mouseout(function() {
mOver = false;
fadeElement(true);
});
});
var fadeElement = function(isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if(items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut);
} else {
console.log("Poof..");
}
}
var makeSlider = function() {
current = (current != null) ? current : items[(items.length-1)];
var currNo = jQuery.inArray(current, items) + 1
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if(faderStat == true)
{
if(!mOver) {
$(items[currNo]).fadeIn((timeOut/6), function() {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
} else {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
faderStat = false;
current = items[currNo];
if(!mOver) {
fadeElement(false);
}
});
}
});
}
} else {
if(!mOver) {
if($(itemsSpan[currNo]).css('bottom') == 0) {
$(itemsSpan[currNo]).slideDown((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
} else {
$(itemsSpan[currNo]).slideUp((timeOut/6), function() {
$(items[currNo]).fadeOut((timeOut/6), function() {
faderStat = true;
current = items[(currNo+1)];
if(!mOver) {
fadeElement(false);
}
});
});
}
}
}
}
makeSlider();
};})(jQuery);
i am struggling modifying this script for almost a week ... please help
Not sure if your still looking for a solution... I've just done this, but thought it would have been a better method to write the li tags out server side by calling them from a random array. That's if your using server side scriptiing - Below is what I did in php.
$arr = array("
Some text", "
Some text", "
Some text", );
$arrCnt = count($arr);
for ($i=0; $i<=$arrCnt; $i++)
{
$random = array_rand($arr);
echo "<li class='sliderImage'>";
echo $arr[$random];
echo "</li>\n";
if($i<$arrCnt-1)
unset($arr[$random]);
}
?>
Hope that helps.

Categories