PHP ajax json on iis - php

New to project and php..Environment IIS 7.5
Trying to get script to retrieve pw to work on IIS.
Link
submitAJAX
function submitAJAX(iPage, iData, iSync) {
if (iSync == null) {
iSync = true;
}
$.ajax({
type: "POST",
dataType: "json",
url: iPage,
global: true,
async: iSync,
data: iData,
success: function(data, textStatus) {
handleAJAXResponse(data, textStatus);
}
});
}
ajax.js
var templateForm;
var desinationForm;
var containerForm;
/*
Wrapper for the JQuery AJAX .post function
*/
function submitAJAX(iPage, iData, iSync) {
if (iSync == null) {
iSync = true;
}
$.ajax({
type: "POST",
dataType: "json",
url: iPage,
global: true,
async: iSync,
data: iData,
success: function(data, textStatus) {
handleAJAXResponse(data, textStatus);
}
});
}
/*
Handle the JQuery AJAX Post response
*/
function handleAJAXResponse(jsonObj, textStatus) {
// Update the destination form
if ((templateForm) && (desinationForm)) {
desinationForm.html(templateForm.html());
containerForm = desinationForm.attr('id');
}
templateForm = '';
desinationForm = '';
if (textStatus == 'success') {
processJSONData(jsonObj, containerForm);
} else {
alert('AJAX Execution Error: ' + textStatus);
}
}
/*
Process the specified JSON data object
*/
function processJSONData(iJSON, iContainer) {
$.each(iJSON, function(iVariable, iValue) {
if (iValue) {
if (iContainer) {
var tmpObj = $('#' + iContainer + ' #' + iVariable);
//if (!tmpObj.size()) { var tmpObj = $('#' + iContainer + " [name=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $('#' + iContainer + " [id*=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $('#' + iContainer + " [name*=" + iVariable + "]"); }
} else {
var tmpObj = $('#' + iVariable);
//if (!tmpObj.size()) { var tmpObj = $("[name=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $("[id*=" + iVariable + "]"); }
//if (!tmpObj.size()) { var tmpObj = $("[name*=" + iVariable + "]"); }
}
// If the current object is another JSON oject
if ((typeof iValue == 'object') && (iValue.toString().indexOf('object') > -1)) {
if (iContainer) {
processJSONData(iValue, iContainer + ' #' + iVariable);
} else {
processJSONData(iValue, iVariable);
}
} else {
//alert(iContainer + '.' + iVariable + ' = ' + iValue + ' : ' + tmpObj.size());
// Object exists on the page
if (tmpObj.size()) {
setFieldValue(tmpObj, iValue);
// Object doesn't exist on the page
} else {
// Check for a JS function
if (iVariable.indexOf('script_') == 0) {
setTimeout(iValue, 10);
//eval(iValue);
// Check for a form validation error
} else if (iVariable.indexOf('_error') > -1) {
setFormError(iVariable.replace('_error', ''));
} else {
//alert('AJAX Variable Error: ' + iVariable);
}
}
}
}
});
}
function setFieldValue(iFieldObj, iValue) {
switch (iFieldObj.attr('type')) {
case 'text':
case 'password':
case 'file':
case 'hidden':
case 'submit':
case 'button':
case 'reset':
case 'textarea':
case 'select-multiple':
iFieldObj.val(iValue);
//alert($(tmpObj).fieldValue());
break;
case 'checkbox':
if (!iFieldObj.attr('checked')) {
iFieldObj.trigger('click');
} else {
//iFieldObj.attr('checked', false);
}
break;
case 'select-one':
iFieldObj.val(iValue);
break;
case 'radio':
$("input[name=" + iFieldObj.attr('id') + "]").each(function() {
if ($(this).val() == iValue) {
$(this).attr('checked', 'checked');
}
});
break;
default:
if ((document.getElementById(iFieldObj.attr('id')).type == 'select-one') || (document.getElementById(iFieldObj.attr('id')).type == 'select-multiple')) {
iFieldObj.val(iValue);
} else if (iFieldObj.attr('id')) {
iFieldObj.html(iValue);
}
break;
}
}
/*
Add the error classes to the specified field
*/
function setFormError(iErrorName) {
if (iErrorName.indexOf(']') > 0) {
var tmpData = iErrorName.split('[');
var tmpIndex = 0;
for (i = 1; i < tmpData.length; i ++) {
tmpData[i] = tmpData[i].replace(']', '');
//if ((tmpData[i] * 1) == 0) { tmpData[i] = 1; }
tmpIndex = tmpIndex + (tmpData[i] * 1);
}
//alert(tmpData[0] + '\n' + tmpIndex);
$('[id*=' + tmpData[0] + ']:input').eq(tmpIndex).addClass('errorElem');
$('[id*=' + tmpData[0] + '_label]').eq(tmpIndex).addClass('errorCell');
} else {
$('#' + iErrorName).addClass('errorElem');
//$("[name=" + iErrorName + "]").addClass('errorElem');
$('#' + iErrorName + '_label').addClass('errorCell');
}
if ($('#updateMsgDescription').size() == 0) {
if (containerForm) {
$('#' + containerForm + ' #updateMsg').after('<div id="updateMsgDescription"></div>');
} else {
$('#updateMsg').after('<div id="updateMsgDescription"></div>');
}
}
/*
var tmpItem = replace($('#' + iErrorName + '_label').html(), ':', '');
tmpItem = Trim(tmpItem.replace(/<\/?(?!\!)[^>]*>/gi, ''));
if (tmpItem != '') {
$('#updateMsgDescription').html($('#updateMsgDescription').html() + '<br>• ' + tmpItem);
}
*/
}
/*
Clean all error elements in the specified form
*/
function clearFormErrors(iFormObj) {
$('.errorElem').removeClass('errorElem');
$('.errorCell').removeClass('errorCell');
}
/*
The error element has been focused so clear any error objects
*/
function cleanFormError(iErrorObj) {
/*
var tmpName = iErrorObj.id || iErrorObj.name || iErrorObj.attr('id') || iErrorObj.attr('name');
if (tmpName) {
$('#' + tmpName).removeClass('errorElem');
//$("[name=" + tmpName + "]").removeClass('errorElem');
$('#' + tmpName + '_label').removeClass('errorCell');
}
*/
$(iErrorObj).removeClass('errorElem');
$(iErrorObj).parent().parent().find('#' + $(iErrorObj).attr('id') + '_label').removeClass('errorCell');
}
/*
Disable a form button, and set updating display label
*/
function doFormSubmit(iDisplay, iForm, iDisabledBtn) {
if (iDisabledBtn == null) {
iDisabledBtn = true;
}
var tmpName = iForm.name || iForm.id || iForm.attr('id');
containerForm = tmpName;
// Clear all form errors
clearFormErrors(iForm);
var tmpType = $(iForm).attr("enctype");
if (tmpType == 'multipart/form-data') {
//alert('file upload');
} else {
if (iDisabledBtn) {
$('#' + tmpName + ' #updateBtn').attr('disabled', true);
}
}
$('#updateMsgDescription').remove();
//$('#' + tmpName + ' #updateBtn').attr('disabled', true);
iDisplay = replace(iDisplay, '...', '<img src=\'images/progress_dots.gif\'>');
$('#' + tmpName + ' #updateMsg').html('<span class="btext12">' + iDisplay + '</span><br><br>');
}
/*
Show a data form for the specified form
*/
function showDataForm(iID, iFormName, iFileName) {
var Now = new Date();
var Start = Now.getTime()
// Remove all existing update forms
//$('[id*=update_]').html('');
//$('[id*=image_]').attr('src', '/images/plus_box.gif');
toggleLinks('update_' + iID, 'image_' + iID);
if (($('#image_' + iID).attr('src')).indexOf('minus') == -1) {
return false;
}
$('#update_' + iID).html('<br><center><b>Loading data...</b></center><br>');
var tmpAddress = window.location.href;
if (tmpAddress.indexOf('?') > 0) {
var tmpDat = tmpAddress.split('?');
tmpAddress = tmpDat[0];
}
templateForm = $('#' + iFormName);
desinationForm = $('#update_' + iID);
if (iFileName == null) {
submitAJAX(tmpAddress + 'add_new.php?action=XML_GET', 1);
//alert(tmpAddress + 'add_new.php?action=XML_GET', { 0: iID });
} else {
submitAJAX(iFileName, {0: iID});
}
var Now = new Date();
//alert((Now.getTime() - Start));
//setTimeout('alert($(\'#update_1 #user_id\').fieldValue());', 2000);
}
I am having issues with other functions using this. What happens when running it is Finding Password... is displayed but it sits there.
Thanks for taking a look,
Doug

Related

MethodNotAllowedHttpException [AJAX]!

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',

Caluclation of a Vat from a value of a javascript function

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']

VeriSign Obtrusive JavaScript interfering with page function

I have this VeriSign script that is causing the javascript notifications on my site to say "undefined" instead of displaying the mesage
Verisign Code:
< !--dn = "www.mysite.com";
lang = "en";
tpt = "transparent";
vrsn_style = "WW";
splash_url = "https://trustsealinfo.verisign.com";
seal_url = "https://seal.verisign.com";
u1 = splash_url + "/splash?form_file=fdf/splash.fdf&dn=" + dn + "&lang=" + lang;
u2 = seal_url + "/getseal?at=0&sealid=2&dn=" + dn + "&lang=" + lang;
u3 = seal_url + "/getseal?at=1&sealid=2&dn=" + dn + "&lang=" + lang;
var sopener;
function vrsn_splash() {
if (sopener && !sopener.closed) {
sopener.focus();
} else {
tbar = "location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500";
var sw = window.open(u1, 'VRSN_Splash', tbar);
if (sw) {
sw.focus();
sopener = sw;
}
}
}
var MM_cVer = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin: 0;
var ver = -1;
var v_ua = navigator.userAgent.toLowerCase();
var re = new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) !== null) {
ver = parseFloat(RegExp.$1);
}
var v_old_ie = (v_ua.indexOf("msie") != -1);
if (v_old_ie) {
v_old_ie = ver < 5;
}
function v_mact(e) {
var s;
if (document.addEventListener) {
s = (e.target.name == "seal");
if (s) {
vrsn_splash();
return false;
}
} else if (document.captureEvents) {
var tgt = e.target.toString();
s = (tgt.indexOf("splash") != -1);
if (s) {
vrsn_splash();
return false;
}
}
return true;
}
function v_mDown(event) {
if (document.addEventListener) {
return true;
}
event = event || window.event;
if (event) {
if (event.button == 1) {
if (v_old_ie) {
return true;
} else {
vrsn_splash();
return false;
}
} else if (event.button == 2) {
vrsn_splash();
return false;
}
} else {
return true;
}
}
function v_resized() {
if (pageWidth != innerWidth || pageHeight != innerHeight) {
self.history.go(0);
}
}
if (plugin) {
var words = navigator.plugins["Shockwave Flash"].description.split(" ");
for (var i = 0; i < words.length;++i) {
if (isNaN(parseInt(words[i], 10))) {
continue;
}
var MM_pVer = words[i];
}
var MM_play = MM_pVer >= MM_cVer;
} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0 && (navigator.appVersion.indexOf("Win") != -1)) {
document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
document.write('on error resume next \n');
document.write('MM_play = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_cVer)))\n');
document.write('</SCR' + 'IPT\> \n');
}
if (MM_play) {
document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
document.write(' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"');
document.write(' ID="s_s" WIDTH="100" HEIGHT="72" ALIGN="">');
document.write(' <PARAM NAME=movie VALUE="' + u3 + '"> <PARAM NAME=loop VALUE=false> <PARAM NAME=menu VALUE=false> <PARAM NAME=quality VALUE=best> <PARAM NAME=wmode VALUE=' + tpt + '> <PARAM NAME="allowScriptAccess" value="always">');
document.write(' <EMBED src="' + u3 + '" loop=false menu=false quality=best wmode=' + tpt);
document.write(' swLiveConnect=FALSE WIDTH="100" HEIGHT="72" NAME="s_s" ALIGN=""');
document.write(' TYPE="application/x-shockwave-flash" PLUGINSPAGE="https://www.macromedia.com/go/getflashplayer" allowScriptAccess="always">');
document.write(' </EMBED>');
document.write(' </OBJECT>');
} else {
document.write("<IMG NAME=\"seal\" BORDER=\"true\" SRC=\"" + u2 + "\" oncontextmenu=\"return false;\" alt=\"Click to Verify - This site has chosen a VeriSign SSL Certificate to improve Web site security\">");
if (document.addEventListener) {
document.addEventListener('mouseup', v_mact, true);
} else {
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = v_mact;
}
}
if (document.layers) {
pageWidth = innerWidth;
pageHeight = innerHeight;
window.onresize = v_resized;
}
}
if ((v_ua.indexOf("msie") != -1) && (ver >= 7)) {
var plat = -1;
var re = new RegExp("windows nt ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) !== null) {
plat = parseFloat(RegExp.$1);
}
if ((plat >= 5.1) && (plat != 5.2)) {
document.write("<div style='display:none'>");
document.write("<img src='https://extended-validation-ssl.verisign.com/dot_clear.gif'/>");
document.write("</div>");
}
}-->
Versign on Page code:
<script type="text/javascript" src="https://seal.verisign.com/getseal?host_name=www.MySite.com&size=S&use_flash=YES&use_transparent=YES&lang=en"> </script>
Affected Javascript:
RemoveItem: function(itemId)
{
if(confirm(lang.CartRemoveConfirm)) {
document.location.href = "cart.php?action=remove&item="+itemId;
}
},
If the code with lang.CartRemoveConfirm belongs to you, it looks like an object with message strings. You should notice that the second row of the VeriSign script redefines lang as the string "en", overriding any value it might have before. Can you use some other variable name?
Same issue here, thinking about using an iframe for the seal on pages that use this lang (CS-Cart vs Verisign).

addEventListener() attached to multiple buttons, but only fires once

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.

FAQ displaying style in JavaScript

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

Categories