I have implemented the following JavaScript in my FAQ page:
var Spry;
if (!Spry) Spry = {};
if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.CollapsiblePanel = function(element, opts)
{
this.init(element);
Spry.Widget.CollapsiblePanel.setOptions(this, opts);
this.attachBehaviors();
};
Spry.Widget.CollapsiblePanel.prototype.init = function(element)
{
this.element = this.getElement(element);
this.focusElement = null;
this.hoverClass = "CollapsiblePanelTabHover";
this.openClass = "CollapsiblePanelOpen";
this.closedClass = "CollapsiblePanelClosed";
this.focusedClass = "CollapsiblePanelFocused";
this.enableAnimation = true;
this.enableKeyboardNavigation = true;
this.animator = null;
this.hasFocus = false;
this.contentIsOpen = true;
};
Spry.Widget.CollapsiblePanel.prototype.getElement = function(ele)
{
if (ele && typeof ele == "string")
return document.getElementById(ele);
return ele;
};
Spry.Widget.CollapsiblePanel.prototype.addClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
return;
ele.className += (ele.className ? " " : "") + className;
};
Spry.Widget.CollapsiblePanel.prototype.removeClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
return;
ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};
Spry.Widget.CollapsiblePanel.prototype.hasClassName = function(ele, className)
{
if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1)
return false;
return true;
};
Spry.Widget.CollapsiblePanel.prototype.setDisplay = function(ele, display)
{
if( ele )
ele.style.display = display;
};
Spry.Widget.CollapsiblePanel.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
if (!optionsObj)
return;
for (var optionName in optionsObj)
{
if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
continue;
obj[optionName] = optionsObj[optionName];
}
};
Spry.Widget.CollapsiblePanel.prototype.onTabMouseOver = function()
{
this.addClassName(this.getTab(), this.hoverClass);
};
Spry.Widget.CollapsiblePanel.prototype.onTabMouseOut = function()
{
this.removeClassName(this.getTab(), this.hoverClass);
};
Spry.Widget.CollapsiblePanel.prototype.open = function()
{
this.contentIsOpen = true;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, true);
this.animator.start();
}
else
this.setDisplay(this.getContent(), "block");
this.removeClassName(this.element, this.closedClass);
this.addClassName(this.element, this.openClass);
};
Spry.Widget.CollapsiblePanel.prototype.close = function()
{
this.contentIsOpen = false;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, false);
this.animator.start();
}
else
this.setDisplay(this.getContent(), "none");
this.removeClassName(this.element, this.openClass);
this.addClassName(this.element, this.closedClass);
};
Spry.Widget.CollapsiblePanel.prototype.onTabClick = function()
{
if (this.isOpen())
this.close();
else
this.open();
this.focus();
};
Spry.Widget.CollapsiblePanel.prototype.onFocus = function(e)
{
this.hasFocus = true;
this.addClassName(this.element, this.focusedClass);
};
Spry.Widget.CollapsiblePanel.prototype.onBlur = function(e)
{
this.hasFocus = false;
this.removeClassName(this.element, this.focusedClass);
};
Spry.Widget.CollapsiblePanel.ENTER_KEY = 13;
Spry.Widget.CollapsiblePanel.SPACE_KEY = 32;
Spry.Widget.CollapsiblePanel.prototype.onKeyDown = function(e)
{
var key = e.keyCode;
if (!this.hasFocus || (key != Spry.Widget.CollapsiblePanel.ENTER_KEY && key != Spry.Widget.CollapsiblePanel.SPACE_KEY))
return true;
if (this.isOpen())
this.close();
else
this.open();
if (e.stopPropagation)
e.stopPropagation();
if (e.preventDefault)
e.preventDefault();
return false;
};
Spry.Widget.CollapsiblePanel.prototype.attachPanelHandlers = function()
{
var tab = this.getTab();
if (!tab)
return;
var self = this;
Spry.Widget.CollapsiblePanel.addEventListener(tab, "click", function(e) { return self.onTabClick(); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(tab, "mouseover", function(e) { return self.onTabMouseOver(); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(tab, "mouseout", function(e) { return self.onTabMouseOut(); }, false);
if (this.enableKeyboardNavigation)
{
// XXX: IE doesn't allow the setting of tabindex dynamically. This means we can't
// rely on adding the tabindex attribute if it is missing to enable keyboard navigation
// by default.
// Find the first element within the tab container that has a tabindex or the first
// anchor tag.
var tabIndexEle = null;
var tabAnchorEle = null;
this.preorderTraversal(tab, function(node) {
if (node.nodeType == 1 /* NODE.ELEMENT_NODE */)
{
var tabIndexAttr = tab.attributes.getNamedItem("tabindex");
if (tabIndexAttr)
{
tabIndexEle = node;
return true;
}
if (!tabAnchorEle && node.nodeName.toLowerCase() == "a")
tabAnchorEle = node;
}
return false;
});
if (tabIndexEle)
this.focusElement = tabIndexEle;
else if (tabAnchorEle)
this.focusElement = tabAnchorEle;
if (this.focusElement)
{
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "focus", function(e) { return self.onFocus(e); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "blur", function(e) { return self.onBlur(e); }, false);
Spry.Widget.CollapsiblePanel.addEventListener(this.focusElement, "keydown", function(e) { return self.onKeyDown(e); }, false);
}
}
};
Spry.Widget.CollapsiblePanel.addEventListener = function(element, eventType, handler, capture)
{
try
{
if (element.addEventListener)
element.addEventListener(eventType, handler, capture);
else if (element.attachEvent)
element.attachEvent("on" + eventType, handler);
}
catch (e) {}
};
Spry.Widget.CollapsiblePanel.prototype.preorderTraversal = function(root, func)
{
var stopTraversal = false;
if (root)
{
stopTraversal = func(root);
if (root.hasChildNodes())
{
var child = root.firstChild;
while (!stopTraversal && child)
{
stopTraversal = this.preorderTraversal(child, func);
try { child = child.nextSibling; } catch (e) { child = null; }
}
}
}
return stopTraversal;
};
Spry.Widget.CollapsiblePanel.prototype.attachBehaviors = function()
{
var panel = this.element;
var tab = this.getTab();
var content = this.getContent();
if (this.contentIsOpen || this.hasClassName(panel, this.openClass))
{
this.removeClassName(panel, this.closedClass);
this.setDisplay(content, "block");
this.contentIsOpen = true;
}
else
{
this.removeClassName(panel, this.openClass);
this.addClassName(panel, this.closedClass);
this.setDisplay(content, "none");
this.contentIsOpen = false;
}
this.attachPanelHandlers();
};
Spry.Widget.CollapsiblePanel.prototype.getTab = function()
{
return this.getElementChildren(this.element)[0];
};
Spry.Widget.CollapsiblePanel.prototype.getContent = function()
{
return this.getElementChildren(this.element)[1];
};
Spry.Widget.CollapsiblePanel.prototype.isOpen = function()
{
return this.contentIsOpen;
};
Spry.Widget.CollapsiblePanel.prototype.getElementChildren = function(element)
{
var children = [];
var child = element.firstChild;
while (child)
{
if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
children.push(child);
child = child.nextSibling;
}
return children;
};
Spry.Widget.CollapsiblePanel.prototype.focus = function()
{
if (this.focusElement && this.focusElement.focus)
this.focusElement.focus();
};
/////////////////////////////////////////////////////
Spry.Widget.CollapsiblePanel.PanelAnimator = function(panel, doOpen, opts)
{
this.timer = null;
this.interval = 0;
this.stepCount = 0;
this.fps = 0;
this.steps = 10;
this.duration = 500;
this.onComplete = null;
this.panel = panel;
this.content = panel.getContent();
this.panelData = [];
this.doOpen = doOpen;
Spry.Widget.CollapsiblePanel.setOptions(this, opts);
// If caller specified speed in terms of frames per second,
// convert them into steps.
if (this.fps > 0)
{
this.interval = Math.floor(1000 / this.fps);
this.steps = parseInt((this.duration + (this.interval - 1)) / this.interval);
}
else if (this.steps > 0)
this.interval = this.duration / this.steps;
var c = this.content;
var curHeight = c.offsetHeight ? c.offsetHeight : 0;
if (doOpen && c.style.display == "none")
this.fromHeight = 0;
else
this.fromHeight = curHeight;
if (!doOpen)
this.toHeight = 0;
else
{
if (c.style.display == "none")
{
// The content area is not displayed so in order to calculate the extent
// of the content inside it, we have to set its display to block.
c.style.visibility = "hidden";
c.style.display = "block";
}
// Unfortunately in Mozilla/Firefox, fetching the offsetHeight seems to cause
// the browser to synchronously re-layout and re-display content on the page,
// so we see a brief flash of content that is *after* the panel being positioned
// where it should when the panel is fully expanded. To get around this, we
// temporarily position the content area of the panel absolutely off-screen.
// This has the effect of taking the content out-of-flow, so nothing shifts around.
// var oldPos = c.style.position;
// var oldLeft = c.style.left;
// c.style.position = "absolute";
// c.style.left = "-2000em";
// Clear the height property so we can calculate
// the full height of the content we are going to show.
c.style.height = "";
this.toHeight = c.offsetHeight;
// Now restore the position and offset to what it was!
// c.style.position = oldPos;
// c.style.left = oldLeft;
}
this.increment = (this.toHeight - this.fromHeight) / this.steps;
this.overflow = c.style.overflow;
c.style.height = this.fromHeight + "px";
c.style.visibility = "visible";
c.style.overflow = "hidden";
c.style.display = "block";
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.start = function()
{
var self = this;
this.timer = setTimeout(function() { self.stepAnimation(); }, this.interval);
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.stop = function()
{
if (this.timer)
{
clearTimeout(this.timer);
// If we're killing the timer, restore the overflow
// properties on the panels we were animating!
if (this.stepCount < this.steps)
this.content.style.overflow = this.overflow;
}
this.timer = null;
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.stepAnimation = function()
{
++this.stepCount;
this.animate();
if (this.stepCount < this.steps)
this.start();
else if (this.onComplete)
this.onComplete();
};
Spry.Widget.CollapsiblePanel.PanelAnimator.prototype.animate = function()
{
if (this.stepCount >= this.steps)
{
if (!this.doOpen)
this.content.style.display = "none";
this.content.style.overflow = this.overflow;
this.content.style.height = this.toHeight + "px";
}
else
{
this.fromHeight += this.increment;
this.content.style.height = this.fromHeight + "px";
}
};
My problem is that I want to close all other row when I click on any one.
change the "Spry.Widget.CollapsiblePanel.prototype.onBlur" section for this:
Spry.Widget.CollapsiblePanel.prototype.onBlur = function(e)
{
this.contentIsOpen = false;
if (this.enableAnimation)
{
if (this.animator)
this.animator.stop();
this.animator = new Spry.Widget.CollapsiblePanel.PanelAnimator(this, false, { duration: this.duration, fps: this.fps, transition: this.transition });
this.animator.start();
}
this.removeClassName(this.element, this.openClass);
this.addClassName(this.element, this.closedClass);
};
Related
I have some problems with routes.
Code: MethodNotAllowedHttpException in RouteCollection.php line 219.
I use ajax and laravel 5.1. I try use google, but I do not understand, I try method "path", and in ajax change "type" to "method". I try GET, but no work.
My ajax:
$.ajax({
type: 'POST',
url: '/placeBet',
dataType: 'json',
data: {
ammount: ammount,
color: color
},
headers: {
'X-CSRF-TOKEN': $('#_token').val()
},
success: function (data) {
if (data['color'] == 'red') {
var currentPlaced = parseInt($('.user_red').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_red').html(currentPlaced);
}
if (data['placedMuch']) {
alertify.error('Max 4 bets in round!');
}
if (data['color'] == 'purple') {
var currentPlaced = parseInt($('.user_black').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_black').html(currentPlaced);
}
if (data['color'] == 'gold') {
var currentPlaced = parseInt($('.user_gold').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_gold').html(currentPlaced);
}
if (data['color'] == 'green') {
var currentPlaced = parseInt($('.user_green').html());
currentPlaced = currentPlaced + parseInt(data['ammount']);
$('.user_green').html(currentPlaced);
}
if (data['baaad'] == true) {
alertify.error('Niu niu!');
return;
}
if (data['improvements'] == true) {
alertify.error('We are working on improvements.');
return;
}
if (data['toLow'] == true) {
alertify.error('Minimum bet is 200 diamonds!');
return;
}
if (data['can_bet'] == false) {
alertify.error('You have withdraw request pending, you cannot bet!');
return;
}
if (data['placed'] != false && data['coins'] != false) {
var coins = data['coins'];
var htmlo = '<div class="chat_message"><div class="top"><div class="right_info">Info Bot</div></div><div class="message">You spent ' + ammount + ' diamonds on ' + data['color'] + '.</div></div>';
$('#chatmessages').append(htmlo);
$('.recents_box').mCustomScrollbar("scrollTo", 'bottom');
$({countNum: $('#currentBallance').html()}).animate({countNum: coins}, {
duration: 1000,
easing: 'linear',
step: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
},
complete: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
}
});
} else if (data['placed'] != false && data['coins'] == '0') {
var coins = data['coins'];
var htmlo = '<div class="chat_message"><div class="top"><div class="right_info">Info Bot</div></div><div class="message">You spent all your diamonds on ' + data['color'] + '.</div></div>';
$('#chatmessages').append(htmlo);
('.recents_box').mCustomScrollbar("scrollTo", 'bottom');
$({countNum: $('#currentBallance').html()}).animate({countNum: coins}, {
duration: 1000,
easing: 'linear',
step: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
},
complete: function () {
$('#currentBallance').html(parseFloat(this.countNum).toFixed(0))
}
});
// swal('Yea', 'You placed a bet to ' + color + '. Your current coins are : ' + coins + '!', 'success');
// $('#betammount').val(0);
} else {
if (data['logged'] == false) {
alertify.error('You need to be log in to use this option!');
} else if (data['coins'] == false) {
alertify.error('You are not that rich!');
// $('#betammount').val(0);
} else if (data['coins'] == '0') {
alertify.error('You are empty!');
//$('#betammount').val(0);
}
}
}
});
My routes:
Route::post('/placeBet', ['as' => 'placeBet', 'uses' => 'RouletteController#placeBet']);
My RoulleteController:
public function placeBet(Request $request)
{
$info = [];
if (Auth::check()) {
$lastID = DB::select("SELECT * FROM roulette_history ORDER BY id DESC LIMIT 1");
$roundID = $lastID[0]->id;
$steamID = Auth::user()->steamId64;
$ammount = $request->All()['ammount'];
$getCountPlaced = \App\placedBets::where('gameID', $roundID)->where('userID64', Auth::user()->steamId64)->count();
if($getCountPlaced > 3) {
$info['placedMuch'] = true;
$info = json_encode($info);
return $info;
}
if($ammount < 1 || !is_numeric($ammount)) {
$info['baaad'] = true;
$info = json_encode($info);
return $info;
}
if ($ammount < 200) {
$info['toLow'] = true;
$info = json_encode($info);
return $info;
}
if(Auth::user()->global_banned > 0) {
$info['baaad'] = true;
$info = json_encode($info);
return $info;
}
$color = $request->All()['color'];
if($color == 'black') {
$color = 'purple';
}
$user_info = \App\User::where('steamId64', Auth::user()->steamId64)->first();
$active_ofer = \App\ofers::where('userID', Auth::user()->steamId64)->count();
$info['active_ofer'] = $active_ofer;
$user_coins = $user_info->coins;
if ($user_coins < $ammount) {
$info['coins'] = false;
$info['placed'] = false;
} else {
$user_coins = $user_coins - $ammount;
$siteProfit = \App\profit::first();
$siteProfitTotal = $siteProfit->siteProfit;
$siteProfitTotal = intval($siteProfitTotal) + intval($ammount);
$updateProfit = DB::update("UPDATE siteProfit SET siteProfit='$siteProfitTotal'");
$user_update = \App\User::where('steamId64', Auth::user()->steamId64)->update(['coins' => $user_coins]);
$info['coins'] = $user_coins;
$active_bet = DB::select("SELECT * FROM roulette_history ORDER BY id DESC LIMIT 1");
$game_id = $active_bet[0]->id;
$placed = DB::insert('insert into placed_bets (color, userID64, ammount, gameID, avatar,url,nick,isStreamer,streamLink) values (?, ?, ?, ?,?,?,?,?,?)', [$color, $steamID, $ammount, $game_id, $user_info->avatar, $user_info->url, $user_info->nick,$user_info->isStreamer,$user_info->steamLink]);
$info['placed'] = true;
$info['ammount'] = $ammount;
$info['color'] = $color;
$info['count'] = $getCountPlaced;
}
$info['logged'] = true;
} else {
$info['coins'] = 0;
$info['logged'] = false;
$info['placed'] = false;
}
$info = json_encode($info);
return $info;
}
If u need source, i can get for us!
In your ajax call, change
$.ajax({
type: 'POST',
to
$.ajax({
method: 'POST',
I have a problem with my Flash (.fla) project. I've connected my flash with database with php script. I used ActionScript 2.0.
The problem is data can show at compile program on AdobeFlash CS6 (CTRL+Enter) but data cant show in datagrid when I open the .swf.
It's my php script
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("modul");
$qr = mysql_query("SELECT * from nilaisiswa");
if (!qr || mysql_num_rows($qr)==0) {
$r_string = '&errorcode=3&msg='.mysql_error().'&';
} else {
$r_string = '&errorcode=0&n='.mysql_num_rows ($qr);
$i = 0;
while ($row = mysql_fetch_assoc ($qr)) {
while (list ($key, $val) = each ($row)) {
$r_string .= '&' . $key . $i . '=' . stripslashes($val);
}
$i++;
}
$r_string .='&';
}
echo $r_string;
?>
And here it's my ActionScript 2.0
var select_lv:LoadVars = new LoadVars();
var insert_lv:LoadVars = new LoadVars();
var delete_lv:LoadVars = new LoadVars();
var today:Date = new Date();
var deleteIndex:Number;
var errorMsgs:Array = [
"",
"Couldn't connect to server",
"Couldn't connect to database",
"Error running query",
"First four entries may not be deleted"];
var filepath:String;
var scoreInfo:Array = [];
var headerListener:Object = {};
headerListener.headerRelease = function(event:Object) {
switch (event.columnIndex) {
case 0:
if (scores_dg.getColumnAt(0).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[0], Array.CASEINSENSITIVE);
}
scores_dg.getColumnAt(0).sortedUp = !scores_dg.getColumnAt(0).sortedUp;
break;
case 1:
if (scores_dg.getColumnAt(1).sortedUp) {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC | Array.DESCENDING);
} else {
scores_dg.sortItemsBy(scores_dg.columnNames[1], Array.NUMERIC);
}
scores_dg.getColumnAt(1).sortedUp = !scores_dg.getColumnAt(1).sortedUp;
break;
}
}
function zerofill(n:Number):String {
if (n<10) return '0' + n.toString();
else return n.toString();
}
filepath = "http://localhost/tesis/";
nickname_ti.maxChars = 50;
date_ti.maxChars = 10;
score_ti.text = 0;
date_ti.text = today.getDate() + '-' + zerofill(today.getMonth()+1) + '-' + zerofill(today.getFullYear());
select_lv.onLoad = function(ok:Boolean) {
if (ok) {
if (this.errorcode=="0") {
for (var i:Number=0; i < this.n; i++) {
scoreInfo.push(
{record:this["id"+i],
nickname:this["nickname"+i],
score:Number(this["score"+i]),
dateposted:this["dateposted"+i]
});
}
scores_dg.columnNames = ["nickname", "score", "dateposted"];
scores_dg.getColumnAt(0).width = 130;
scores_dg.getColumnAt(0).sortOnHeaderRelease = false;
scores_dg.getColumnAt(0).sortedUp = false;
scores_dg.getColumnAt(0).headerText = "Nickname";
scores_dg.getColumnAt(1).width = 130;
scores_dg.getColumnAt(1).sortOnHeaderRelease = false;
scores_dg.getColumnAt(1).sortedUp = false;
scores_dg.getColumnAt(1).headerText = "Score";
scores_dg.getColumnAt(2).width = 130;
scores_dg.getColumnAt(2).headerText = "Date Posted";
scores_dg.dataProvider = scoreInfo;
scores_dg.addEventListener("headerRelease", headerListener);
msg_ta.text = "Enter data and click Add to add a score.";
} else {
msg_ta.text = errorMsgs[Number(this.errorcode)];
if (this.errorcode == "3") msg_ta.text += ": " + this.msg;
}
} else {
msg_ta.text = "Flash-database select operation failed";
}
}
msg_ta.text = "Getting high scores from database...";
select_lv.sendAndLoad(filepath + "getscores.php", select_lv, "GET");
I have an sql-database, where data can be read out by an html-form. The data are shown in an html-table, this works fine! However, I would like to make the table sortable, which means, that by clicking on the respective field-name the data should be sorted according to this field (ascending/descending). I have tried different javaScript-solutions including tablesorter.com that work well in "normal" tables, however, not in this table that is built dynamically with data from a database. Here is my code that creates the table (code without specific link to JavaScript-files):
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql) or die("Invalid query"); //Running the
query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
$row = mysqli_fetch_array($result);
if ($numrows > 0) {
echo "<table id=myTable class=tablesorter>";
echo "<thead><tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr></thead>";
echo "<tbody><tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr></tbody>";
}
echo "</table>";
}
}
mysqli_close($db);
?>
One of the javaScript-files I tried:
(function () {
"use strict";
var tableSort = function (tab) {
var titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[
0].getElementsByTagName("th");
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen == 0) return;
var nspalten = tz[0].cells.length;
var arr = new Array(nzeilen);
var sortiert = -1;
var sorttype = new Array(nspalten);
var sortbuttonStyle = document.createElement
('style'); // Stylesheet für Button im TH
sortbuttonStyle.innerText =
'.sortbutton { width:100%; height:100%; border:
none; background-color: transparent; font: inherit; color: inherit; text-
align: inherit; padding: 0; cursor: pointer; } .sortbutton::-moz-focus-
inner { margin: -1px; border-width: 1px; padding: 0; }';
document.head.appendChild(sortbuttonStyle);
var initTableHead = function (sp) { // Kopfzeile
vorbereiten
var b = document.createElement("button");
b.type = "button";
b.className = "sortbutton";
b.innerHTML = titel[sp].innerHTML;
b.addEventListener("click", function () {
tsort(sp);
}, false);
titel[sp].innerHTML = "";
titel[sp].appendChild(b);
}
var getData = function (ele, s) {
var val = ele.innerHTML;
if (!isNaN(val) && val.search(/[0-9]/) !
= -1) return val;
var n = val.replace(",", ".");
if (!isNaN(n) && n.search(/[0-9]/) !=
-1) return n;
sorttype[s] = "s"; // String
return val;
} // getData
var vglFkt_s = function (a, b) {
var as = a[sortiert],
bs = b[sortiert];
if (as > bs) return 1;
else return -1;
} // vglFkt_s
var vglFkt_n = function (a, b) {
return parseFloat(a[sortiert]) -
parseFloat(b[sortiert]);
} // vglFkt_n
var tsort = function (sp) {
if (sp == sortiert) arr.reverse(); //
Tabelle ist schon nach dieser Spalte sortiert, also nur Reihenfolge
umdrehen
else { // Sortieren
sortiert = sp;
if (sorttype[sp] == "n")
arr.sort(vglFkt_n);
else arr.sort(vglFkt_s);
}
for (var z = 0; z < nzeilen; z++)
tbdy.appendChild(arr[z][nspalten]); // Sortierte Daten zurückschreiben
} // tsort
// Kopfzeile vorbereiten
for (var i = 0; i < titel.length; i++) initTableHead(i);
// Array mit Info, wie Spalte zu sortieren ist,
vorbelegen
for (var s = 0; s < nspalten; s++) sorttype[s] = "n";
// Tabelleninhalt in ein Array kopieren
for (var z = 0; z < nzeilen; z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
arr[z] = new Array(nspalten + 1);
arr[z][nspalten] = tz[z];
for (var s = 0; s < nspalten; s++) {
var zi = getData(zelle[s], s);
arr[z][s] = zi;
// zelle[s].innerHTML
+= "<br>"+zi+"<br>"+sorttype[s]; // zum Debuggen
}
}
} // tableSort
var initTableSort = function () {
var sort_Table = document.querySelectorAll
("table.sortierbar");
for (var i = 0; i < sort_Table.length; i++) new
tableSort(sort_Table[i]);
} // initTable
if (window.addEventListener) window.addEventListener("DOMContentLoaded",
initTableSort, false); // nicht im IE8
})();
Another of the javaScript-files I tried:
( function() {
"use strict";
var JB_sortbutStyle = document.createElement('style'); // Stylesheet
für Button im TH
JB_sortbutStyle.innerText = 'button.sortbut { width:100%; height:100%;
border: none; background-color: transparent; font: inherit; color:
inherit; text-align: inherit; padding: 0; cursor: pointer; }
button.sortbut::-moz-focus-inner { margin: -1px; border-width: 1px;
padding: 0; }';
document.head.appendChild(JB_sortbutStyle);
var JB_Table = function(tab) {
var up = String.fromCharCode(9650);
var down = String.fromCharCode(9660);
// var up = String.fromCharCode(8593);
// var down = String.fromCharCode(8595);
// var up = String.fromCharCode(11014);
// var down = String.fromCharCode(11015);
var no = String.fromCharCode(160,160,160,160); // Idee: 9674 ???
var dieses = this;
var defsort = 0;
var startsort_u = -1,startsort_d = -1;
var first = true;
var ssort;
var tbdy = tab.getElementsByTagName("tbody")[0];
var tz = tbdy.rows;
var nzeilen = tz.length;
if (nzeilen==0) return;
var nspalten = tz[0].cells.length;
var Titel = tab.getElementsByTagName("thead")
[0].getElementsByTagName("tr")[0].getElementsByTagName("th");
var Arr = new Array(nzeilen);
var ct = 0;
var sdir = new Array(nspalten);
var stype = new Array(nspalten);
var sortable = new Array(nspalten);
for(var i=0;i<nspalten;i++) {
stype[i] = "n";
sdir[i] = "u";
sortable[i] = false;
}
var initTableHead = function(t,nr) {
var b = document.createElement("button");
b.type = "button";
b.className = "sortbut"
b.innerHTML = t.innerHTML;
t.innerHTML = "";
if(window.addEventListener) b.addEventListener
("click",function() { dieses.sort(nr); },false);
b.title = 'Die Tabelle nach "'+b.textContent+'"
sortieren.';
t.appendChild(b);
sortsymbol.init(t,no);
if(t.className.indexOf("vorsortiert-")>-1) {
sortsymbol.set(t,down);
ssort = nr;
}
else if(t.className.indexOf("vorsortiert")>-1) {
sortsymbol.set(t,up);
ssort = nr;
}
if(t.className.indexOf("sortiere-")>-1) startsort_d=nr;
else if(t.className.indexOf("sortiere")>-1)
startsort_u=nr;
sortable[nr] = true;
} // initTableHead
var sortsymbol = {
init: function(t,s) {
var tt = t.querySelector("button");
var sp = tt.getElementsByTagName("span");
for(var i=0;i<sp.length;i++) {
if(!sp[i].hasChildNodes()) {
t.sym = sp[i].appendChild
(document.createTextNode(s));
break;
}
}
if(typeof(t.sym)=="undefined") t.sym =
tt.appendChild(document.createTextNode(s));
},
set: function(t,s) {
t.sym.data = s;
},
get: function(t) {
return t.sym.data;
}
} // sortsymbol
var VglFkt_s = function(a,b) {
var as = a[ssort], bs = b[ssort];
var ret=(as>bs)?1:(as<bs)?-1:0;
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { as = a[defsort]; bs
= b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort])
}
return ret;
} // VglFkt_s
var VglFkt_n = function(a,b) {
var ret = parseFloat(a[ssort])-parseFloat(b[ssort]);
if(!ret && ssort!=defsort) {
if (stype[defsort]=="s") { var as = a
[defsort],bs = b[defsort]; ret = (as>bs)?1:(as<bs)?-1:0; }
else ret = parseFloat(a[defsort])-parseFloat(b
[defsort]);
}
return ret;
} // VglFkt_n
var convert = function(val,s) {
var dmy;
var trmdat = function() {
if(dmy[0]<10) dmy[0] = "0" + dmy[0];
if(dmy[1]<10) dmy[1] = "0" + dmy[1];
if(dmy[2]<10) dmy[2] = "200" + dmy[2];
else if(dmy[2]<20) dmy[2] = "20" + dmy[2];
else if(dmy[2]<99) dmy[2] = "19" + dmy[2];
else if(dmy[2]>9999) dmy[2] = "9999";
}
if(val.length==0) val = "0";
if(!isNaN(val) && val.search(/[0-9]/)!=-1) return val;
var n = val.replace(",",".");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
n = n.replace(/\s| | |\u00A0/g,"");
if(!isNaN(n) && n.search(/[0-9]/)!=-1) return n;
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
dmy[5] = val.substring(dp+4,dp+6);
for(var i=0;i<6;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<6;i++) if(dmy[i]<10) dmy[i] = "0"
+ dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]+dmy[5]).replace(/ /g,"");
}
if(!val.search
(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+\s+\d+:\d\d\s*$/)) {
var dp = val.search(":");
dmy = val.substring(0,dp-2).split(".");
dmy[3] = val.substring(dp-2,dp);
dmy[4] = val.substring(dp+1,dp+3);
for(var i=0;i<5;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
for(var i=3;i<5;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[2]+dmy[1]+dmy[0]+"."+dmy[3]+dmy
[4]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<3;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]+"."+dmy[2]).replace
(/ /g,"");
}
if(!val.search(/^\s*\d+:\d\d\s*$/)) {
dmy = val.split(":");
for(var i=0;i<2;i++) dmy[i] = parseInt(dmy
[i],10);
for(var i=0;i<2;i++) if(dmy[i]<10) dmy[i]
= "0"+dmy[i];
return (""+dmy[0]+dmy[1]).replace(/ /g,"");
}
if(!val.search(/^\s*\d+\s*\.\s*\d+\s*\.\s*\d+/)) {
dmy = val.split(".");
for(var i=0;i<3;i++) dmy[i] = parseInt(dmy
[i],10);
trmdat();
return (""+dmy[2]+dmy[1]+dmy[0]).replace
(/ /g,"");
}
stype[s] = "s";
// return val.toLowerCase().replace(/
\u00e4/g,"ae").replace(/\u00f6/g,"oe").replace(/\u00fc/g,"ue").replace(/
\u00df/g,"ss");
return val.toLowerCase().replace(/\u00e4/g,"a ").replace
(/\u00f6/g,"o ").replace(/\u00fc/g,"u ").replace(/\u00df/g,"ss");
} // convert
this.sort = function(sp) {
if(sp<0 || sp>=nspalten) return;
if(!sortable[sp]) return;
if (first) {
for(var z=0;z<nzeilen;z++) {
var zelle = tz[z].getElementsByTagName
("td"); // cells;
Arr[z] = new Array(nspalten+1);
Arr[z][nspalten] = tz[z];
for(var s=0;s<nspalten;s++) {
if (zelle[s].getAttribute("data-
sort_key"))
var zi = convert(zelle
[s].getAttribute("data-sort_key"),s);
else if (zelle[s].getAttribute
("sort_key"))
var zi = convert(zelle
[s].getAttribute("sort_key"),s);
else
var zi = convert(zelle
[s].textContent,s);
Arr[z][s] = zi ;
// zelle[s].innerHTML
+= "<br>"+zi; // zum Debuggen
}
}
first = false;
}
if(sp==ssort) {
Arr.reverse() ;
if ( sortsymbol.get(Titel[ssort])==down )
sortsymbol.set(Titel[ssort],up);
else
sortsymbol.set(Titel[ssort],down);
}
else {
if ( ssort>=0 && ssort<nspalten ) sortsymbol.set
(Titel[ssort],no);
ssort = sp;
if(stype[ssort]=="s") Arr.sort(VglFkt_s);
else Arr.sort(VglFkt_n);
if(sdir[ssort]=="u") {
sortsymbol.set(Titel[ssort],up);
}
else {
Arr.reverse() ;
sortsymbol.set(Titel[ssort],down);
}
}
for(var z=0;z<nzeilen;z++)
tbdy.appendChild(Arr[z][nspalten]);
if(typeof(JB_aftersort)=="function") JB_aftersort
(tab,tbdy,tz,nzeilen,nspalten,ssort);
} // sort
if(!tab.title.length) tab.title="Ein Klick auf die
Spalten\u00fcberschrift sortiert die Tabelle.";
for(var i=Titel.length-1;i>-1;i--) {
var t=Titel[i];
if(t.className.indexOf("sortier")>-1) {
ct++;
initTableHead(t,i);
defsort = i ;
if(t.className.indexOf("sortierbar-")>-1) sdir
[i] = "d";
}
}
if(ct==0) {
for(var i=0;i<Titel.length;i++)
initTableHead(Titel[i],i);
defsort = 0;
}
if(startsort_u>=0) this.sort(startsort_u);
if(startsort_d>=0) { this.sort(startsort_d); this.sort
(startsort_d); }
if(typeof(JB_aftersortinit)=="function") JB_aftersortinit
(tab,tbdy,tz,nzeilen,nspalten,-1);
} // JB_Table
var JB_initTableSort = function() {
if (!document.querySelectorAll) return;
var JB_Tables = [];
var Sort_Table = document.querySelectorAll("table.sortierbar,
table[sortable]");
for(var i=0;i<Sort_Table.length;i++) JB_Tables.push(new JB_Table
(Sort_Table[i]));
var pars = decodeURI(window.location.search.substring(1));
if(pars.length) { // jbts=((0,1),(10,0),(3,3),(2,2)) tnr,snr
pars = pars.replace(/\s/g,"");
pars = pars.match(/jbts=\(?(\(\d+,\d+\),?){1,}\)?/gi);
if(pars) {
pars = pars[0].substr(pars[0].search("=")+1);
pars = pars.replace(/\(\(/g,"(").replace(/\)
\)/g,")").replace(/\)\(/g,")|(").replace(/\),\(/g,")|(");
pars = pars.split("|");
for(var i=0;i<pars.length;i++) {
var p = pars[i].substring(1,pars
[i].length-1).split(",");
if(p[0]>-1&&p[0]<JB_Tables.length)
JB_Tables[p[0]].sort(p[1]);
}
}
}
} // initTableSort
if(window.addEventListener) window.addEventListener
("DOMContentLoaded",JB_initTableSort,false);
})();
I would be more than happy if anybody could help me with this Problem!
I used tablesorter for same purpose. I created table dynamically from database and it worked. First add to table id="myTable". After just call the script by adding code below:
$(document).ready(function()
{
$("#myTable").tablesorter();
}
);
Note: Don't forget to include src="jquery.tablesorter.js" (download it from download link).
Now you should be able to sort your table by all columns by just clicking on table header of column.
EDIT:
Insted of:
echo "<table id=myTable class=tablesorter>";
Put:
echo "<table id='myTable' class='tablesorter'>";
How about sorting the table before displaying?
For example, if your link to the page is:
http://example.com/view/product_table
The code for querying the table is:
function getTable($order = null) {
$statement = "SELECT * FROM product_table";
if ($order) {
// switch case to prevent sql injection
switch ($order) {
case: "price":
$statement .= " ORDER BY product_price";
break;
}
}
// Continue the build sql here
}
Have the sorting button redirect to:
http://example.com/view/product_table?sort=price
Call function by:
getTable($GET[sort]);
To further my answer
I would suggest separating the code responsible for displaying and the code for building data
Name your variable to something more meaningful
Currently your code is very hard to maintain and read.
Hello everyone I need help
then I have a form that through a javascript function I calculate the total of a product and then mail
Now I want to calculate the VAT on that value , but it does not work and I understand why , perhaps , the value that gives me is a value not a number for example he gives me 100 Euros .. not 100 and then I wanted to know , if is a system to extract the number to that value and then let him calculate the VAT
thank you
I guess this is what you need..
Try explode(). This function returns you an array of strings.
$valueWithCurrency = "100 Euros";
$extractedValue = explode(' ', $valueWithCurrency); //space as a delimiter in first argument
echo $extractedValue[0]; //Here you go. "100"
echo $extractedValue[1]; //this contains "Euros"
sorry .
This is the plug-in code that I purchased
(function($) {
$.fn.SimplePriceCalc= function (options) {
// Default options for text
var settings = $.extend({
totallabel: "Total:",
detailslabel: "Details:",
currency:"$"
}, options );
// Initialize Variables
var total=0;
var child=this.find('*');
var formdropdowns=this.find('select');
this.addClass("simple-price-calc");
InitialUpdate();
// Change select data cost on each change to current selected value
formdropdowns.change( function() {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
var selectedOptionstotal=0;
if (selectedOptions != '')
{
selectedOptions.each( function() {
selectedOptionstotal += $(this).data('price');
});
}
$(this).attr('data-total',selectedOptionstotal);
}
else{
var selectedOption = $(this).find(':selected');
if($(this).data('mult') >= 0)
$("#simple-price-total label").attr('data-mult',selectedOption.val());
else
$(this).attr('data-total',selectedOption.data('price')) ;
}
UpdateTotal();
});
//Update total when user inputs or changes data from input box
$(".simple-price-calc input[type=text]").change( function() {
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else if(userinput != '') { alert('Please enter a valid number'); var usernumber = 1; } else { usernumber = 1; }
var multiple=parseFloat($(this).data('mult')) || 0;
var pricecost=parseFloat($(this).data('price')) || 0;
var percentage=$(this).data('prcnt') || 1;
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
$(this).attr('data-total', updpricecost);
}
if(multiple && multiple !=0) {
$("#simple-price-total label").attr('data-mult',usernumber);
}
}
UpdateTotal();
});
$(".simple-price-calc input[type=checkbox]").change( function() {
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
$(this).attr('data-total', checkboxval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
UpdateTotal();
});
$(".simple-price-calc input[type=radio]").change( function() {
$(".simple-price-calc input[type=radio]").each( function() {
if($(this).is(':checked')) {
var radioval= $(this).val();
if($.isNumeric(radioval)) {
$(this).attr('data-total', radioval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
UpdateTotal();
});
//Initialize all fields if data is there
function InitialUpdate() {
formdropdowns.each( function() {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
var selectedOptionstotal=0;
if (selectedOptions != '')
{
selectedOptions.each( function() {
selectedOptionstotal += $(this).data('price');
});
}
$(this).attr('data-total',selectedOptionstotal);
}
else{
var selectedOption = $(this).find(':selected');
$(this).attr('data-total',selectedOption.data('price')) ;
}
});
//Update total when user inputs or changes data from input box
$(".simple-price-calc input[type=text]").each( function() {
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else if(userinput != '') { alert('Please enter a valid number'); var usernumber = 1;} else { usernumber = 1; }
var multiple=parseFloat($(this).data('mult')) || 0;
var pricecost=parseFloat($(this).data('price')) || 0;
var percentage=$(this).data('prcnt') || 1;
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
$(this).attr('data-total', updpricecost);
}
if(multiple && multiple !=0) {
$("#simple-price-total label").attr('data-mult',usernumber);
}
}
});
$(".simple-price-calc input[type=checkbox]").each( function() {
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
$(this).attr('data-total', checkboxval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
$(".simple-price-calc input[type=radio]").each( function() {
if($(this).is(':checked')) {
var radioval= $(this).val();
if($.isNumeric(radioval)) {
$(this).attr('data-total', radioval);
}
else {
$(this).attr('data-total', 0);
}
}
else {
$(this).attr('data-total', 0);
}
});
UpdateTotal();
}
//Change value of total field by adding all data totals in form
function UpdateTotal() {
total=0;
totalmult=$(".simple-price-calc #simple-price-total label").attr("data-mult");
//For each input with data-merge attr, take merge ids value and multiply by current data-price
$("input[data-merge]").each(function(){
var ids=$(this).data('merge');
var ids=ids.split(',');
var arraytotals=1;
$.each(ids, function(key,value) {
var inputid =$("#"+value);
if( (inputid.attr('type') == 'checkbox' || inputid.attr('type') == 'radio') && inputid.is(':checked') )
arraytotals*=$("#"+value).val();
else if (inputid.attr('type') == 'text')
arraytotals*=$("#"+value).val();
else if (inputid.prop('nodeName') == "SELECT")
arraytotals*=$("#"+value).attr('data-total');
});
var idtotal=arraytotals;
if($.isNumeric(idtotal)) {
var pricecost=parseFloat($(this).data('price')) || 0;
$(this).val(idtotal);
var updpricecost= pricecost * parseFloat($(this).val());
$(this).attr('data-total',updpricecost);
}
});
child.each(function () {
itemcost= $(this).attr("data-total") || 0;
total += parseFloat(itemcost);
});
if(totalmult) { total = total * parseFloat(totalmult); }
$(".simple-price-calc #simple-price-total label").html(settings.currency+$.number(total,2));
setTimeout(function() {
UpdateDescriptions();
}, 100);
}
//Update Field Labels and Pricing
function UpdateDescriptions() {
var selectedformvalues= [];
var currtag='';
$(".simple-price-calc").find('*').each( function () {
currtag=$(this).prop('tagName');
if(currtag == "SELECT") {
if($(this).attr('multiple')) {
var selectedOptions = $(this).find(':selected');
if (selectedOptions != '')
{
selectedOptions.each( function() {
var optionlabel= $(this).data('label') || '';
var optionprice = $(this).data('price');
if(optionlabel != '') {
selectedformvalues.push(optionlabel + ": " + settings.currency + optionprice);
}
});
}
}
else{
var selectedOption = $(this).find(':selected');
if (selectedOption != '')
{
var optionlabel= selectedOption.data('label') || '';
var optionprice = selectedOption.data('price');
if(optionlabel != '') {
selectedformvalues.push(optionlabel +": " + settings.currency + optionprice);
}
}
}
} // End of Form dropdown
if(currtag == "INPUT" && $(this).attr('type') == "text")
{
if($(this).attr('data-price') || $(this).attr('data-mult')) {
var userinput= $(this).val();
if($.isNumeric(userinput)) { var usernumber = parseFloat(userinput);} else { var usernumber = 1; }
var pricecost=parseFloat($(this).data('price')) || 0;
var currlabel= $(this).attr('data-label') || '';
var currinput= userinput;
if (currlabel != '' && currinput !='') {
if($.isNumeric(pricecost) && pricecost !=0) {
var updpricecost=pricecost * usernumber;
selectedformvalues.push(currlabel + ": " + settings.currency + updpricecost);
}
else{
selectedformvalues.push(currlabel + ": " + currinput);
}
}
}
} // End of input type text
if($("input[type=checkbox]") || $("input[type=radio]") )
{
if($(this).is(':checked')) {
var checkboxval= $(this).val();
if($.isNumeric(checkboxval)) {
var currlabel= $(this).attr('data-label') || '';
var currprice= checkboxval;
if (currlabel != '') { selectedformvalues.push(currlabel + ": " + settings.currency + currprice); }
}
}
} // End of input type checkbox or radio
});
$("#simple-price-details").html("");
if (selectedformvalues != '') {
$("#simple-price-details").append("<h3>"+ settings.detailslabel +"</h3>");
$.each(selectedformvalues, function(key,value) {
$("#simple-price-details").append(value + "<br />");
});
}
}// End of UpdateDescriptions()
this.append('<div id="sidebar"><div id="simple-price-total"><h3 style="margin:0;">' + settings.totallabel + ' </h3><label id="simple-price-total-num"> ' + settings.currency + $.number(total,2) + ' </label></div> <div id="simple-price-details"></div></div>');
return this;
}; // End of plugin
}(jQuery));
This is the call in html
// Attaches Simple Price Calc to form
$("#quoteform").SimplePriceCalc();
// Adds Total price and details to hidden inputs that can be used to e-mail data
$("form :input, form textarea, form select").change( function() {
setTimeout( function() {
var total=$('#simple-price-total-num').html();
var details=$('#simple-price-details').html();
$('#hiddentotal').val(total);
$('#hiddendetails').val(details);
}, 150);
});
in php use this to have the value
echo $_POST['hidden_total']
I am writing a Facebook app in PHP/FBJS. I have some code where I attach an addEventListener() to two buttons. When I run the app, the first button I click on fires the addEventListener() and the event handler is invoked as expected. But if I click on the second button or click on the same button again, the event handler is not invoked. Here is my code:
//PHP
public function loadCargoDialogFbjsAction() {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$loadableCargo = $this->getRequest()->getPost('loadableCargo');
$fbjs =
'<div id="load_cargo_select">
<form id="load_cargo_select_form" action="" method="POST">
<p>Your train has stopped in the city of ' . $loadableCargo['city'] . '</p>
<p>' . $loadableCargo['city'] . ' produces the following goods:</p>
<ul>';
if(count($loadableCargo['city_goods']) <= 0) {
$fbjs .= '<li>None</li>';
} else {
foreach($loadableCargo['city_goods'] as $goods) {
$fbjs .= '<li>' . $goods['name'] . '</li>';
}
}
$fbjs .=
'</ul>
<p>Your train is hauling the following goods:</p>
<ul>';
if(count($loadableCargo['train_goods']) <= 0) {
$fbjs .= '<li>None</li>';
} else {
foreach($loadableCargo['train_goods'] as $goods) {
$fbjs .= '<li>' . $goods['name'] . '</li>';
}
}
$fbjs .=
'</ul>
<p>What would you like to do?</p>
<input type="button" id="load-new-submit" name="load-cargo-new" value="Load new goods" />
<input type="button" id="discard-existing-submit" name="load-cargo-discard" value="Discard existing goods" />
</form>
</div>';
echo $fbjs;
}
// JavaScript/FBJS
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', cargoEventHandler); //loadNewCargo);
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', cargoEventHandler); //discardExistingCargo);
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
dialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
dialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
function cargoEventHandler(evt) {
//new Dialog().showMessage('loadNewCargo', 'city id='+cityId+', train id='+trainId);
//debugger;
cityId = evt.target.cityId;
trainId = evt.target.trainId;
switch(evt.target.getId()) {
case 'load-new-submit':
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Load new goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
openCargoHolds = data.openCargoHolds;
cargoHoldsUsed = 0;
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'cityGoods': data.cityGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
//debugger;
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Load cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-new', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-new-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
break;
case 'discard-existing-submit':
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Discard existing goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'trainGoods': data.trainGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
var dialog = new Dialog().showChoice('Discard Cargo', fbjsData, 'Discard cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-discard', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-discard-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
break;
}
return false;
}
Any help would be greatly appreciated. Thanks!
#Tim
I changed my loadCargo() function as follows to prevent duplication of those elements, but I am still running into the same problem as before.
var loadCargoDialog;
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
if(loadCargoDialog == null) {
loadCargoDialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', cargoEventHandler, true); //loadNewCargo);
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', discardExistingCargo, true);
} else {
loadCargoDialog.showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
}
loadCargoDialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
loadCargoDialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
loadCargoDialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
It looks like you might be creating elements with the same id. That would cause it to break.