Caluclation of a Vat from a value of a javascript function - php

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

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

PHP ajax json on iis

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

Couldn't establish an ajax connection using jQuery, form automatically submits?

I am quite a newbie on Jquery and just faced a problem that I'm not able to get over.
I, simply, have an HTML form with a few elements on a page. I want to validate the form values upon clicking the submit button, and then insert some of the form values to a db using JQuery. Right after the insert process completed successfully, I want the form to be submitted naturally.
I made the validation work, and get all to values successfully from the form, but I am not able to connect to the PHP page. I have two pages.
Here is the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$("#odeme").submit(function() {
$('#ok').attr('disabled', 'disabled');
$("#ok").after('<span id="info" style="font-size:8pt;color:green;padding-left:5px;"><img align="absmiddle" src="loading.gif" border="0" /> Ödemeniz Yapılıyor</span>');
//değişkenler
var jad = $("#ad").val().length;
var jsoyad = $("#soyad").val().length;
var jadres = $("#adres").val().length;
var jeposta = $("#eposta").val().length;
var isEposta = $("#eposta").val();
var epostaReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jsehir = $("#sehir").val();
var jtaksit = $("#taksit").val();
var jkartisim = $("#kartisim").val().length;
var jkartno = $("#kartno").val().length;
var jkartay = $("#kartay").val();
var jkartyil = $("#kartyil").val();
var jkartcvv = $("#kartcvv").val().length;
var hasError = false;
// kontrollere başla
if (jad < 6) {
$('#ad').css('border', 'solid 1px red');
hasError = true;
}
if (jsoyad < 2) {
$('#soyad').css('border', 'solid 1px red');
hasError = true;
}
if (jadres < 10) {
$('#adres').css('border', 'solid 1px red');
hasError = true;
}
if (jeposta < 6) {
$('#eposta').css('border', 'solid 1px red');
hasError = true;
}
if (jsehir == 0) {
$('#sehir').css('border', 'solid 1px red');
hasError = true;
}
if (jtaksit == 20) {
$('#taksit').css('background', '#FF9494');
hasError = true;
}
if (jkartisim < 6) {
$('#kartisim').css('border', 'solid 1px red');
hasError = true;
}
if (jkartno < 15) {
$('#kartno').css('border', 'solid 1px red');
hasError = true;
}
if (jkartay == 0) {
$('#kartay').css('border', 'solid 1px red');
hasError = true;
}
if (jkartyil == 0) {
$('#kartyil').css('border', 'solid 1px red');
hasError = true;
}
if (jkartcvv != 3) {
$('#kartcvv').css('border', 'solid 1px red');
hasError = true;
}
if ($('#sozlesme').is(':checked')) {
hasError = false;
} else {
$('#sozlesme').css('outline-color', 'red');
$('#sozlesme').css('outline-style', 'solid');
$('#sozlesme').css('outline-width', 'thin');
hasError = true;
}
if (!epostaReg.test(isEposta)) {
$('#eposta').css('border', 'solid 1px red');
hasError = true;
}
if (hasError == true) {
$("#info").remove();
$("#ok").after('<span id="errorSpan" style="color:red;padding-left:5px;">Lütfen formu eksiksiz doldurunuz.</span>');
$("#errorSpan").delay(3000).fadeOut(2000);
$('#ok').removeAttr("disabled");
return false;
} else {
// form verilerini db ye at
var form_ad = $("#ad").val();
var form_soyad = $("#soyad").val();
var form_adres = $("#adres").val();
var form_eposta = $("#eposta").val();
var form_sehir = $("#sehir").val();
var form_taksit = $("#taksit").val();
var form_telno = $("#telno").val();
var form_cinsiyet = $("#cinsiyet").val();
var dataString = 'ad='+ form_ad +
'&soyad=' + form_soyad +
'&adres=' + form_adres +
'&eposta=' + form_eposta +
'&sehir=' + form_sehir +
'&taksit=' + form_taksit +
'&telno=' + form_telno +
'&cinsiyet=' + form_cinsiyet;
alert(dataString);
JQuery.ajax({
type: "POST",
url: "form.php",
data: dataString,
cache: false,
success: function(result){
if(result == 1) {
alert(result);
return false; }
else {
$("#ok").after('<span id="errorSpan" style="color:red;padding-left:5px;">Lütfen formu eksiksiz doldurunuz.</span>');
}
}
});
}
});
});
</script>
and here is the code of the form.php
<?php
If (!isset($_POST['ad'])) {
echo 0;
}
else {
$ad = $_POST['ad'];
If ($ad == "asdasd") {
echo 1;
} else {
echo 0;
}
}
?>
I have read all the questions asked about this issue and try to apply all the solutions, but I'm stucked :/
Try this:
$(document).ready(function() {
$("#odeme").submit(function() {
//validation
//and
//ajax
return false; //this suppresses default form submission behaviour
});
});

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