I am trying to use "query" object to perform what i want. Everythings works except when i select an option nothing happen (placeholder is not replaced).
I have followed the instructing from this post Loading remote data only once with Select2
init() {
this.$view.select2({
theme: "bootstrap",
language: "fr",
allowClear: this.options.allowClear,
placeholder: this.options.placeholder,
query: (query) => {
if (this.items) {
query.callback({results: this.filterItems(query.term)});
} else {
this.loadData(query);
}
},
templateResult: (state) => {
return this.format(state);
}
});
}
loadData(query) {
$.ajax({
url: this.options.url,
dataType: 'json',
type: 'GET',
success: (data) => {
this.items = [];
for (let row of data) {
this.items.push({
id: row.id,
entity_id: row.entity_id,
text: row.label,
type: row.type,
disabled: !row.enable
});
}
query.callback({results: this.items});
}
});
}
filterItems(term) {
if (typeof term == "undefined" || term === null) {
return this.items;
}
const _term = $.trim(term.toLowerCase());
if (_term === '') {
return this.items;
}
return this.items.filter((item) => {
return item.text.toLowerCase().includes(term);
});
}
Thanx for help,
I think i have found a solution :
var s2data = $view.select2({
ajax: {
url: 'https://api.github.com/search/repositories',
data: {
q: 'select2'
},
dataType: 'json',
processResults: function(data) {
var items = [];
for (var row of data.items) {
items.push({
id: row.id,
text: row.name
});
}
this.options.set('cacheDataSource', {items: items});
return {
results: items
};
}
},
cacheDataSource: [],
allowClear: true,
placeholder: 'Select Values ...',
width: '100%',
}).data('select2');
s2data.dataAdapter.query = function(params, callback) {
var cacheDataSource = this.options.get('cacheDataSource');
if (cacheDataSource && cacheDataSource.items) {
var term = params.term;
if (typeof term == "undefined" || term == null) {
callback({results: cacheDataSource.items});
return
}
term = $.trim(term.toLowerCase());
if (term == "") {
callback({results: cacheDataSource.items});
return
}
callback({ results: cacheDataSource.items.filter(function(item) {
return item.text.toLowerCase().includes(term);
})
});
} else {
// call the original logic
var ajaxAdapterFunc = jQuery.fn.select2.amd.require('select2/data/ajax');
var ajaxAdapter = new ajaxAdapterFunc(this.$element, this.options);
ajaxAdapter.query(params, callback);
}
}
jsfiddle : https://jsfiddle.net/3kpu4htm/35/
Related
sorry for my bad english. I just wanna ask about select2 ajax, i have problem with this, i don't know how to get other response from my API.
So this is the response from my API.
enter image description here
so i want to get zip_code value when select2 has on changed. but i don't know to get it.
this my code..
$(".myselect").select2(
{
theme: "bootstrap4",
placeholder: "Provinsi, Kota/Kab, Kecamatan, Kelurahan",
minimumInputLength: 3,
ajax: {
url: url, //changing by env
dataType: 'json',
type: "GET",
delay: 150,
data: function (params) {
return {
filter: params.term
};
},
processResults: function (data, params) {
var res = data.data.locations.map(function (item) {
return {
id: item.id,
text: item.name,
zip: item.zip_code
};
});
return {
results: res
};
},
templateResult: function(result) {
return result.text;
},
templateSelection: function(selection) {
return selection.text;
}
},
}).on('change.select2', function(e){
console.log($(this).val(e.text));
villText = $("#village option:last-child").text();
var villVal = $("#village option:last-child").val();
// console.log($("#village option:last-child").val())
// var villVal1 = $("#village option:last-child").val();
villKel = villText;
villKel = villKel.split(',')[2];
$("#village_kel").val(villKel);
var villx = $('#village_land');
var vill_land = $("#village_land option:last-child").text();
vill_land_kel = vill_land;
vill_land_kel = vill_land_kel.split(',')[2];
$("#villageland_kel").val(vill_land_kel);
$('input[name="domisili"]').click(function() {
if ($(this).attr("value") == "1") {
if(villx.empty()) {
villx.append($('<option></option>').attr('value', villVal).text(villText));
villx.prop('selectedIndex', 0);
}
else {
villx.append($('<option></option>').attr('value', "").text(""));
}
}
})
});
picture below is the result when i get the text of value from my API.
enter image description here
I have a button which calculate some items in my TreeStore. When I click on it I want to reload my tree. But now when I click on an item to calculate it, create another tree like same one under selected item and then reload new one. How can I write appropriate code for this problem?
This is my function when click on calculate button:
'g-infitmformula #calculateFormula': {
click: function (sender) {
var selectedinfoIdList = Ext.ComponentQuery.query("g-infitmformula")[0].getSelectionModel().getSelection();
Ext.each(selectedinfoIdList, function (item) {
informationItemIds.push(item.data.id);
});
if (selectedinfoIdList.length > 0) {
Dufo.Func.loadMask(Ext.getBody(), true);
Ext.Ajax.request({
url: '/sis/rest/infoit/calculateFormula',
jsonData: {
infoItemStrings: informationItemIds
},
success: function (result, request) {
var data = Ext.JSON.decode(result.responseText).ReturnValue;
Ext.Msg.alert('', data.description);
Dufo.Func.loadMask(Ext.getBody(), false);
if (data.successful === true) {
// Ext.ComponentQuery.query('g-infitmformula')[0].store.reload();
Ext.ComponentQuery.query("g-infitmformula")[0].store.reload({
params: {
id: "root",
dtstart: dtstartVar,
dtend: dtendVar,
infitmcat: infitmcatVar
}
});
informationItemIds = [];
}
else {
informationItemIds = [];
Ext.Msg.alert('', data.description);
}
},
failure: function (result, request) {
Dufo.Func.loadMask(Ext.getBody(), false);
informationItemIds = [];
Ext.Msg.alert('', Ext.JSON.decode(result.responseText).ReturnValue.description || Dufo.ux.fa.jsonFormatFail);
}
});
} else {
Ext.Msg.alert('', Dufo.ux.fa.selectSomething);
}
}
}
This is my store class which I want to reload:
Ext.define('Dufo.store.InformationItemsFormula', {
extend: 'Ext.data.TreeStore',
storeId: 'infitmformula',
model: 'Dufo.model.InformationItemsFormula',
autoLoad: false,
nodeParam: 'id',
clearOnLoad: true,
listeners: {
append: function (parent, child, index, eOpts) {
var me = this;
if (!child.isRoot()) {
child.set('leaf', child.get('isLeaf'));
if (child.data.children) {
var root = me.tree.treeStore.getRootNode();
child.data.children.forEach(function (test) {
var n = root.createNode(test);
child.appendChild(n);
});
}
}
}
},
proxy: {
type: 'ajax',
url: '/sis/rest/infitmval/gtinffmlitmval',
actionMethods: {
read: 'POST', create: 'POST'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
jsonData: true,
reader: {
type: 'json',
root: function (o) {
if (o.ReturnValue) {
if(o.ReturnValue.detail.length) {
Ext.ComponentQuery.query("#calculateFormula")[0].setDisabled(false);
}else {
Ext.ComponentQuery.query("#calculateFormula")[0].setDisabled(true);
}
for (var i=0; i < o.ReturnValue.detail.length; i++) {
o.ReturnValue.detail[i].id = o.ReturnValue.detail[i].id + '-' +Dufo.store.TreeStoreIDGenerator.generateId();
}
return o.ReturnValue.detail;
}
}
}
}
});
You below code is creating issue because you are explicitly create same node. Those node will be also created by Extjs it self.
listeners: {
append: function (parent, child, index, eOpts) {
var me = this;
if (!child.isRoot()) {
child.set('leaf', child.get('isLeaf'));
if (child.data.children) {
var root = me.tree.treeStore.getRootNode();
child.data.children.forEach(function (test) {
var n = root.createNode(test);
child.appendChild(n);
});
}
}
}
Remove this code because append listeners can be use to perform some operation no newly created node. This is basically call from Called from a node's appendChild method.
I have a textbox with id txtAutocompletePortal.
How can I open autocomplete menu on focus of textbox?
Here is my code :
Mod.SmartSearch = function (smartSearchOptions) {
if (typeof (smartSearchOptions) == "undefined" || smartSearchOptions == null) { smartSearchOptions = {}; };
var sS = {
smartSearchOptions: $.extend({
'autoFocus': false,
'source': function (reuqest, resonse) {
},
'minLength': 0,
'delay': 100,
'select': function (event, ui) {
},
'messages': {
noResults: '',
results: function () { }
},
}, smartSearchOptions),
_form: '',
_searchFieldId: '',
_context: '',
_reset: {},
_validate: {},
_init: function () {
$(this.searchFieldId, this.context).autocomplete(this.smartSearchOptions);
$(this.searchFieldId, this.context).autocomplete("option", "appendTo", this._searchFieldId)
}
};
return {
form: sS._form,
searchFieldId: sS._searchFieldId,
context: sS._context,
init: sS._init,
reset: sS._reset,
validator: sS._validate,
smartSearchOptions: sS.smartSearchOptions
};
};
var source = function (request, response) {
if (request.term.search(/[a-z A-Z 0-9]\s/) > 0) {
return;
}
else {
$.ajax({
url: url + "/" + agentId + "/" +
Mod.ExtractLast(request.term),
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
}
}));
}
});
}
};
var select = function (event, ui) {
event.preventDefault();
if (ui.item) {
App.ContactInfo.portalId = ui.item.value;
App.ContactInfo.portalName = ui.item.label;
selctedPortalId = ui.item.value;
selctedPortalName = ui.item.label;
this.value = ui.item.label;
}
};
var ss = Mod.SmartSearch({ source: source, select: select });
ss.searchFieldId = '#txtAutocompletePortal';
ss.context = '#PortalBodySrch';
ss.init();
To make jQuery Autocomplete pop up when the user click the box, use this:
var field = $( /*whatever selector */ );
field.autocomplete({
minLength: 0,
/* extra settings, as needed */
}).focus(function(){
$(this).data("uiAutocomplete").search($(this).val());
});
Currently BigCommerce has this hide/show effect only displaying one step of the checkout process at a time. It's rather an annoying accordion. I am trying to have the accordion info all open on the page. Also, I would love to combined and/or change the steps order. Any help with any of this would be great! Here is an example of the JS being used for the checkout process.
var ExpressCheckout = {
completedSteps: new Array(),
currentStep: 'AccountDetails',
signedIn: 0,
digitalOrder: 0,
createAccount: 0,
anonymousCheckout: 0,
checkoutLogin: 0,
init: function()
{
if($('#CheckoutStepAccountDetails').css('display') == 'none') {
ExpressCheckout.currentStep = 'BillingAddress';
}
else {
$('#BillingDetailsLabel').html(lang.ExpressCheckoutStepBillingAccountDetails);
}
$('.ExpressCheckoutBlock').hover(function() {
if($(this).hasClass('ExpressCheckoutBlockCompleted')) {
$(this).css('cursor', 'pointer');
}
},
function() {
$(this).css('cursor', 'default');
});
$('.ExpressCheckoutTitle').click(function() {
if($(this).hasClass('ExpressCheckoutBlockCompleted')) {
$(this).find('.ChangeLink').click();
}
});
// Capture any loading errors
$(document).ajaxError(function(event, request, settings) {
ExpressCheckout.HideLoadingIndicators();
alert(lang.ExpressCheckoutLoadError);
});
},
Login: function()
{
$('#CheckoutLoginError').hide();
ExpressCheckout.anonymousCheckout = 0;
ExpressCheckout.createAccount = 0;
if(ExpressCheckout.validateEmailAddress($('#login_email').val()) == false) {
alert(lang.LoginEnterValidEmail);
$('#login_email').focus();
$('#login_email').select();
return false;
}
if($('#login_pass').val() == '') {
alert(lang.LoginEnterPassword);
$('#login_pass').focus();
return false;
}
ExpressCheckout.ShowLoadingIndicator('#LoginForm');
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=expressCheckoutLogin&'+$('#LoginForm').serialize(),
success: ExpressCheckout.HandleResponse
});
return false;
},
HandleResponse: function(response)
{
ExpressCheckout.HideLoadingIndicators();
if(response.completedSteps != undefined) {
$.each(response.completedSteps, function() {
var value = document.createTextNode(this.message);
$('#CheckoutStep'+this.id+' .ExpressCheckoutCompletedContent').html(value);
$('#CheckoutStep'+this.id).addClass('ExpressCheckoutBlockCompleted');
ExpressCheckout.completedSteps[ExpressCheckout.completedSteps.length] = this.id;
});
}
if(response.stepContent != undefined) {
$.each(response.stepContent, function() {
$('#CheckoutStep'+this.id+' .ExpressCheckoutContent').html(this.content);
$('#CheckoutStep'+this.id+' .ExpressCheckoutContent .FormField.JSHidden').show();
});
}
ExpressCheckout.HandleResponseStatus(response);
},
HandleResponseStatus: function(response)
{
if(response.status == 0) {
if(response.errorContainer) {
$(response.errorContainer).html(response.errorMessage).show();
}
else {
alert(response.errorMessage);
}
}
if(response.changeStep) {
ExpressCheckout.ChangeStep(response.changeStep);
ExpressCheckout.ResetNextSteps();
}
// Set focus to a particular field
if(response.focus) {
try {
$(response.focus).focus().select();
}
catch(e) { }
}
},
GuestCheckout: function()
{
$('#CreateAccountForm').show();
$('#CheckoutLoginError').hide();
if($('#CheckoutGuestForm').css('display') != 'none' && !$('#checkout_type_register:checked').val()) {
type = 'guest';
ExpressCheckout.anonymousCheckout = 1;
ExpressCheckout.createAccount = 0;
}
else {
type = 'account';
ExpressCheckout.anonymousCheckout = 0;
ExpressCheckout.createAccount = 1;
}
ExpressCheckout.ShowLoadingIndicator('#CheckoutGuestForm');
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: {
w: 'expressCheckoutGetAddressFields',
type: type
},
success: ExpressCheckout.HandleResponse
});
},
ResetNextSteps:function()
{
steps = ExpressCheckout.GetSteps();
var beginReset = false;
var newCompleted = Array();
$.each(steps, function(i, step) {
if(step == ExpressCheckout.currentStep) {
newCompleted[newCompleted.length] = step;
beginReset = true;
}
else if(beginReset == true) {
$('#CheckoutStep'+step).removeClass('ExpressCheckoutBlockCompleted');
$('#CheckoutStep'+step+' .ExpressCheckoutCompletedContent').html('');
}
});
ExpressCheckout.completedSteps = newCompleted;
},
ChangeStep: function(step)
{
if(typeof(step) == 'undefined') {
step = ExpressCheckout.CalculateNextStep(ExpressCheckout.currentStep);
}
if(step == ExpressCheckout.currentStep) {
return false;
}
$('#CheckoutStep'+ExpressCheckout.currentStep+' .ExpressCheckoutContent').slideUp('slow');
$('#CheckoutStep'+ExpressCheckout.currentStep).addClass('ExpressCheckoutBlockCollapsed');
if($.inArray(ExpressCheckout.currentStep, ExpressCheckout.completedSteps) != -1) {
$('#CheckoutStep'+ExpressCheckout.currentStep).addClass('ExpressCheckoutBlockCompleted');
}
$('#CheckoutStep'+step+' .ExpressCheckoutContent').slideDown('slow');
$('#CheckoutStep'+step).removeClass('ExpressCheckoutBlockCollapsed');
ExpressCheckout.currentStep = step;
return false;
},
GetSteps: function()
{
var steps = Array();
if(ExpressCheckout.signedIn == 0) {
steps[steps.length] = 'AccountDetails';
}
steps[steps.length] = 'BillingAddress';
if(!ExpressCheckout.digitalOrder) {
steps[steps.length] = 'ShippingAddress';
steps[steps.length] = 'ShippingProvider';
}
steps[steps.length] = 'Confirmation';
steps[steps.length] = 'PaymentDetails';
return steps;
},
CalculateNextStep: function(currentStep) {
steps = ExpressCheckout.GetSteps();
var nextStep = '';
$.each(steps, function(i, step) {
if(step == currentStep) {
nextStep = steps[i + 1];
}
});
if(nextStep) {
return nextStep;
}
},
ChooseBillingAddress: function()
{
// Chosen to use a new address?
if(!$('#BillingAddressTypeExisting:checked').val() || $('#ChooseBillingAddress').css('display') == 'none') {
// If creating a new account, validate the account fields as well
if((ExpressCheckout.anonymousCheckout || ExpressCheckout.createAccount) &&
!ExpressCheckout.ValidateNewAccount(true)) {
return false;
}
if(!ExpressCheckout.ValidateNewAddress('billing')) {
return false;
}
addressType = 'new';
}
// An address wasn't selected
else if($('.SelectBillingAddress select option:selected').val() == -1) {
alert(lang.ExpressCheckoutChooseBilling);
$('.SelectBillingAddress select').focus();
return false;
}
else {
addressType = 'existing';
}
createAppend = '';
if(ExpressCheckout.createAccount) {
createAppend = '&createAccount=1';
}
// ISC-1214: no script issue in webkit browser, with serialized form submission
$('noscript').remove();
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=saveExpressCheckoutBillingAddress&'
+ $('#NewBillingAddress').serialize()
+ '&BillingAddressType=' + addressType
+ createAppend,
success: ExpressCheckout.HandleResponse
});
return false;
},
ChooseShippingAddress: function(copyBilling)
{
// Chosen to use a new address?
if(!$('#ShippingAddressTypeExisting:checked').val() || $('#ChooseShippingAddress').css('display') == 'none') {
if(!ExpressCheckout.ValidateNewAddress('shipping')) {
return false;
}
addressType = 'new';
}
// An address wasn't selected
else if($('.SelectShippingAddress select option:selected').val() == -1) {
alert(lang.ExpressCheckoutChooseShipping);
$('.SelectShippingAddress select').focus();
return false;
}
else {
addressType = 'existing';
}
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=saveExpressCheckoutShippingAddress&'
+$('#NewShippingAddress').serialize()
+'&ShippingAddressType='+addressType,
success: ExpressCheckout.HandleResponse
});
return false;
},
SetBillingAndShippingAddress: function()
{
// billing address is pre-selected so update the HTML block content from selected index
billingAddress = $('.SelectBillingAddress select option:selected').html().substring(0, 58);
$('#CheckoutStepBillingAddress .ExpressCheckoutCompletedContent').html(billingAddress + '...');
$('#CheckoutStepBillingAddress').addClass('ExpressCheckoutBlockCompleted');
// select given shipping address and reset the cart step to ShippingProvider
ExpressCheckout.ChooseShippingAddress();
return false;
},
ChooseShippingProvider: function()
{
// A shipping provider hasn't been selected
var shippingValid = true;
$('#CheckoutStepShippingProvider .ShippingProviderList').each(function() {
if(!$(this).find('input[type=radio]:checked').val()) {
alert(lang.ExpressCheckoutChooseShipper);
$(this).find('input[type=radio]').get(0).focus();
shippingValid = false;
return false;
}
});
if(shippingValid == false) {
return false;
}
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: 'w=saveExpressCheckoutShippingProvider&'+$('#CheckoutStepShippingProvider form').serialize(),
success: ExpressCheckout.HandleResponse
});
return false;
},
ShowLoadingIndicator: function(step) {
if(typeof(step) == 'undefined') {
step = 'body';
}
$(step).find('.ExpressCheckoutBlock input[type=submit]').each(function() {
$(this).attr('oldValue', $(this).val());
$(this).val(lang.ExpressCheckoutLoading);
$(this).attr('disabled', true);
});
$(step).find('.LoadingIndicator').show();
$('body').css('cursor', 'wait');
},
HideLoadingIndicators: function()
{
HideLoadingIndicator();
$('.ExpressCheckoutBlock input[type=submit]').each(function() {
if($(this).attr('oldValue') && $(this).attr('disabled') == true) {
$(this).val($(this).attr('oldValue'));
$(this).attr('disabled', false);
}
});
$('.LoadingIndicator').hide();
$('body').css('cursor', 'default');
},
LoadOrderConfirmation: function()
{
postVars.w = 'expressCheckoutShowConfirmation';
$.ajax({
url: 'remote.php',
type: 'post',
dataType: 'json',
data: postVars,
success: ExpressCheckout.HandleResponse
});
},
HidePaymentForm: function()
{
$('#CheckoutStepPaymentDetails').hide();
$('#CheckoutStepPaymentDetails .ExpressCheckoutContent').html('');
},
LoadPaymentForm: function(provider)
{
$.ajax({
url: 'remote.php',
data: 'w=expressCheckoutLoadPaymentForm&'+$('#CheckoutStepConfirmation form').serialize(),
dataType: 'json',
type: 'post',
success: ExpressCheckout.HandleResponse
});
},
ShowSingleMethodPaymentForm: function()
{
$('#CheckoutStepPaymentDetails').show();
ShowContinueButton();
},
ValidateNewAccount: function()
{
var password, confirmPassword, formfield = FormField.GetValues(CustomCheckoutFormNewAccount);
for (var i=0; i<formfield.length; i++) {
// Check email
if (formfield[i].privateId == 'EmailAddress') {
if (ExpressCheckout.validateEmailAddress(formfield[i].value) == false) {
alert(lang.LoginEnterValidEmail);
FormField.Focus(formfield[i].field);
return false;
}
}
if (formfield[i].privateId == 'Password') {
if(!ExpressCheckout.createAccount) {
continue;
}
password = formfield[i];
}
else if(formfield[i].privateId == 'ConfirmPassword') {
if(!ExpressCheckout.createAccount) {
continue;
}
confirmPassword = formfield[i];
}
var rtn = FormField.Validate(formfield[i].field);
if (!rtn.status) {
alert(rtn.msg);
FormField.Focus(formfield[i].field);
return false;
}
}
// Compare the passwords
if (ExpressCheckout.createAccount && password && password.value !== confirmPassword.value) {
alert(lang.AccountPasswordsDontMatch);
FormField.Focus(confirmPassword.field);
return false;
}
return true;
},
BuildAddressLine: function(type)
{
var fieldList = {
'FirstName' : '',
'LastName' : '',
'Company' : '',
'AddressLine1' : '',
'City' : '',
'State' : '',
'Zip' : '',
'Country' : ''
};
if(type == 'billing') {
var formId = CustomCheckoutFormBillingAddress;
}
else {
var formId = CustomCheckoutFormShippingAddress;
}
var formfields = FormField.GetValues(formId);
var addressLine = '';
for (var i=0; i<formfields.length; i++) {
fieldList[formfields[i].privateId] = formfields[i].value;
}
for (var i in fieldList) {
var val = fieldList[i];
if (val !== '') {
if(addressLine != '' && i != 'LastName') {
addressLine += ', ';
} else if(i == 'LastName') {
addressLine += ' ';
}
addressLine += val;
}
};
return addressLine;
},
ValidateNewAddress: function(lowerType, resultOnly)
{
if (resultOnly !== true) {
resultOnly = false;
}
if(lowerType == 'billing') {
var formId = CustomCheckoutFormBillingAddress;
} else {
var formId = CustomCheckoutFormShippingAddress;
}
var formfields = FormField.GetValues(formId);
var hasErrors = false;
for (var i=0; i<formfields.length; i++) {
var rtn = FormField.Validate(formfields[i].field);
if (!rtn.status) {
if (!resultOnly) {
alert(rtn.msg);
}
FormField.Focus(formfields[i].field);
hasErrors = true;
return false;
}
}
if(hasErrors == true) {
return false;
}
else {
return true;
}
},
validateEmailAddress: function(email)
{
if(email.indexOf('#') == -1 || email.indexOf('.') == -1) {
return false;
}
return true;
},
ToggleAddressType: function(address, type)
{
if(type == 'Select') {
$('.Select'+address+'Address').show();
$('.Add'+address+'Address').hide();
}
else {
$('.Add'+address+'Address').show();
$('.Select'+address+'Address').hide();
}
},
SelectedPaymentProvider: function() {
var paymentProvider = '';
// Get the ID of the selected payment provider
if($('#use_store_credit').css('display') != "none") {
if($('#store_credit:checked').val()) {
if($('#credit_provider_list').css('display') != "none") {
paymentProvider = $('#credit_provider_list input:checked');
}
}
else {
paymentProvider = $('#provider_list input:checked');
}
}
else {
paymentProvider = $('#provider_list input:checked');
}
return paymentProvider
},
ConfirmPaymentProvider: function()
{
//if terms and conditions is enabled and the customer didn't tick agree terms and conditions
if($('.CheckoutHideOrderTermsAndConditions').css('display') != "none" && $('#AgreeTermsAndConditions').prop('checked') != true){
alert(lang.TickArgeeTermsAndConditions);
return false;
}
if(!confirm_payment_provider()) {
return false;
}
var paymentProvider = ExpressCheckout.SelectedPaymentProvider();
if(paymentProvider != '' && $(paymentProvider).hasClass('ProviderHasPaymentForm')) {
var providerName = $('.ProviderName'+paymentProvider.val()).html();
$('#CheckoutStepConfirmation .ExpressCheckoutCompletedContent').html(providerName);
ExpressCheckout.LoadPaymentForm($(paymentProvider).val());
return false;
}
else {
ExpressCheckout.HidePaymentForm();
return true;
}
},
ApplyCouponCode: function()
{
if($('#couponcode').val() == '') {
alert(lang.EnterCouponCode);
$('#couponcode').focus();
return false;
}
// Reload the order confirmation
$.ajax({
url: 'remote.php',
data: 'w=getExpressCheckoutConfirmation&'+$('#CheckoutStepConfirmation form').serialize(),
dataType: 'json',
type: 'post',
success: ExpressCheckout.HandleResponse
});
return false;
},
UncheckPaymentProvider: function()
{
$('#provider_list input').each(function() {
$(this).attr('checked', false);
});
}
};
I could get the top three accordions open at the same time (the bottom ones are shipping methods and order confirmations, which I think are tied to the previous steps)
$('.ExpressCheckoutBlockCollapsed').addClass('ExpressCheckoutBlockCompleted')
$('.ExpressCheckoutBlockCollapsed').removeClass('ExpressCheckoutBlockCollapsed')
I think if you have this code trigger on the checkout page, it might help a little. Regarding changing the order of elements, chrome console shows the following IDs associated with these elements, can't you anchor them to different locations, as you need it?
$('.ExpressCheckoutBlockCollapsed').addClass('ExpressCheckoutBlockCompleted')
[
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCompleted" id="CheckoutStepBillingAddress" style="cursor: default;">…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepShippingAddress" style>…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepShippingProvider" style>…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepConfirmation">…</div>
,
<div class="Clear ExpressCheckoutBlock ExpressCheckoutBlockCollapsed ExpressCheckoutBlockCompleted" id="CheckoutStepPaymentDetails" style="display: none">…</div>
]
i have a problem. I am trying to add a functions return value to a variable but it says the function is undefined. Here is my code. :
var selectedExpenseList = getSelectedExpenseIDs();
here is my function:
function getSelectedExpenseIDs() {
var selectedExpensesList = new Array;
var i = 0;
$('.expenseCheckBox:checked').each(function () {
if ($(this)[0].id !== "checkAllExpenses") {
selectedExpensesList[i] = $(this)[0].id.split('_')[1];
++i;
}
});
return selectedExpensesList;
}
EDIT: here is my entire function: I am trying to delete something from a list if a person has checked it.
var selectedExpenseList;
function actuallyDeleteTheExpense(canDeleteExpenses)
{
selectedTasksList = getSelectedTaskIDs();
var deleteTrackers = false, deleteExpenses = false;
if (canDeleteExpenses && !canDeleteTrackers)
{
$.Zebra_Dialog('Do you wish to remove Expenses?',
{
'type': 'question',
'title': 'Confirmation',
'buttons': [
{
caption: 'Yes', callback: function () {
deleteTrackers = false;
deleteExpenses = true;
doTheDelete(deleteExpenses);
}
},
{
caption: 'No',
callback: function () {
doTheDelete(deleteExpenses);
}
}
]
});
}
}
function doTheDelete(doIDeleteExpenses)
{
if (selectedTasksList.length > 0)
{
$.ajax({
type: "POST",
//url: "/Tasks/ViewTasks.aspx/deleteTasksAndLinkedItems",
url: '<%=ResolveUrl("~/Expenses/ViewExpenses.aspx/deleteSelectedExpense")%>',
data: "{ 'TaskIDs': [" + selectedTasksList.join(',') + "], DeleteTrackers : " + doIDeleteTrackers + ", DeleteExpenses : " + doIDeleteExpenses + " }",
//fix data
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var ss = data.d;
if (ss.length > 0) {
for (var i = 0; i < ss.length; ++i) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true });
alert(ss[i]);
}
}
$("#viewTasksGrid").flexReload();
},
error: function (data) {
$.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true, modal: true });
alert('Error Deleting Tasks');
if (window.console) {
console.log(data);
}
}
});
} else {
showMessage('No tasks are selected.');
}
}
//end delete expense
function getSelectedExpenseIDs() {
var selectedExpensesList = new Array;
var i = 0;
$('.expenseCheckBox:checked').each(function () {
if ($(this)[0].id !== "checkAllExpenses") {
selectedExpensesList[i] = $(this)[0].id.split('_')[1];
++i;
}
});
return selectedExpensesList;
}
I noticed that your function code is tabbed once more than your code that calls it. It's possible that your function is scoped improperly (e.g. it's declared inside another function and you're calling it from outside that function).
If your function is coming back as undefined, it's almost certainly a scoping issue. I see nothing wrong with the function itself.
For instance:
$(document).ready(function () {
function myFunction() {
return 3;
}
});
var bob = myFunction(); //Error: myFunction is not defined.