Square Up payment gateway form with ajax - javascript

I am creating a new payment option in website. I implemented the square space successfully. But it creates issue when some one removes any item from the cart.
When ajax is called, it loads the whole content again. but then, form doesn't load and shows console error undefined object SqPaymentForm.
var sqPaymentForm = new SqPaymentForm({
// Replace this value with your application's ID (available from the merchant dashboard).
// If you're just testing things out, replace this with your _Sandbox_ application ID,
// which is also available there.
applicationId: '***********',
inputClass: 'sq-input',
cardNumber: {
elementId: 'sq-card-number',
placeholder: "0000 0000 0000 0000"
},
cvv: {
elementId: 'sq-cvv',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: 'Postal Code'
},
inputStyles: [
// Because this object provides no value for mediaMaxWidth or mediaMinWidth,
// these styles apply for screens of all sizes, unless overridden by another
// input style below.
{
fontSize: '14px',
padding: '3px'
},
// These styles are applied to inputs ONLY when the screen width is 400px
// or smaller. Note that because it doesn't specify a value for padding,
// the padding value in the previous object is preserved.
{
mediaMaxWidth: '400px',
fontSize: '18px',
}
],
callbacks: {
cardNonceResponseReceived: function(errors, nonce, cardData) {
if (errors) {
var errorDiv = document.getElementById('errors');
errorDiv.innerHTML = "";
errors.forEach(function(error) {
var p = document.createElement('p');
p.innerHTML = error.message;
errorDiv.appendChild(p);
});
} else {
// This alert is for debugging purposes only.
alert('Nonce received! ' + nonce + ' ' + JSON.stringify(cardData));
// Assign the value of the nonce to a hidden form element
var nonceField = document.getElementById('card-nonce');
nonceField.value = nonce;
// Submit the form
document.getElementById('form').submit();
}
},
unsupportedBrowserDetected: function() {
// Alert the buyer that their browser is not supported
}
}
});
I am using default code provided by gateway doc. Payment option is addon of event manager pro.

It looks like you have forgotten to include this line
<script type="text/javascript" src="https://js.squareup.com/v2/paymentform"></script>
Also note that Square and Squarespace are very different companies.

JSFiddle Link
`
/* onGetCardNonce is triggered when the "Pay $1.00" button is clicked */
function onGetCardNonce(event) {
/* Don't submit the form until SqPaymentForm returns with a nonce */
event.preventDefault();
/* Request a nonce from the SqPaymentForm object */
paymentForm.requestCardNonce();
}
function Initialize(){
console.log("Initialize square");
/* Create and initialize a payment form object */
const paymentForm = new SqPaymentForm({
/* Initialize the payment form elements*/
/* TODO: Replace with your sandbox application ID */
applicationId: "{API_KEY}",
inputClass: 'sq-input',
autoBuild: false,
/* Customize the CSS for SqPaymentForm iframe elements*/
inputStyles: [{
fontSize: '16px',
lineHeight: '24px',
padding: '16px',
placeholderColor: '#a0a0a0',
backgroundColor: 'transparent',
}],
/* Initialize the credit card placeholders */
cardNumber: {
elementId: 'sq-card-number',
placeholder: '{card_number}',
},
cvv: {
elementId: 'sq-cvv',
placeholder: '{cvv}',
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: '{mmyy}',
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: '{postal}',
},
/*SqPaymentForm callback functions*/
callbacks: {
/*
* callback function: cardNonceResponseReceived
* Triggered when: SqPaymentForm completes a card nonce request
*/
cardNonceResponseReceived: function (errors, nonce, cardData) {
var errorDiv = $("#square-form-error");
errorDiv.html("");
if (errors) {
/* Log errors from nonce generation to the browser developer console. */
console.error('Encountered errors:');
errors.forEach(function (error) {
console.error(' ' + error.message);
errorDiv.append('<div class="alert alert-danger m-t-15"><strong>' + error.message + '</strong></div>');
});
/*alert('Encountered errors, check browser developer console for more details');*/
return;
}
/* add card_nonce and card_zip parameters */
var $nonceInput = $('<input/>').attr({'name':'card_nonce','value':nonce,'type':'text'});
var $billingPostalCode = $('<input/>').attr({'name':'card_zip','value':cardData.billing_postal_code,'type':'text'});
$('#square-form-container').append($nonceInput);
$('#square-form-container').append($billingPostalCode);
/* submit form */
$('#square-form-container').closest('form')[0].submit();
/*nonce */
},
unsupportedBrowserDetected: function() {
/* Alert the buyer that their browser is not supported*/
alert("browser does not support ");
}
}
});
/* call after Initialization*/
paymentForm.build();
}
(function() {
setTimeout(function() { Initialize(); }, 5000);
})();
`

Related

Advanced card payments SDK showing error during submission of form

Error: "Hosted Fields payment is already in progress."
I have copied it from this PayPal documentation, and in the SDK URL pass a proper sandbox clientID.
if (paypal.HostedFields.isEligible()) {
paypal.HostedFields.render({
createOrder: function () {return "order-ID";}, // replace order-ID with the order ID
styles: {
'input': {
'font-size': '17px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'card number'
},
cvv: {
selector: '#cvv',
placeholder: 'card security number'
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'mm/yy'
}
}
}).then(function (hf) {
$('#my-sample-form').submit(function (event) {
event.preventDefault();
hf.submit({
// Cardholder Name
cardholderName: document.getElementById('card-holder-name').value,
// Billing Address
billingAddress: {
streetAddress: document.getElementById('card-billing-address-street').value, // address_line_1 - street
extendedAddress: document.getElementById('card-billing-address-unit').value, // address_line_2 - unit
region: document.getElementById('card-billing-address-state').value, // admin_area_1 - state
locality: document.getElementById('card-billing-address-city').value, // admin_area_2 - town / city
postalCode: document.getElementById('card-billing-address-zip').value, // postal_code - postal_code
countryCodeAlpha2: document.getElementById('card-billing-address-country').value // country_code - country
}
});
});
});
}
You need to replace "order-ID" with an actual PayPal Order ID created for this checkout.
There are several ways to obtain one. See https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-side-api-calls for how to call the orders API from your server to 'Create Order' and 'Capture Order'. You should use these to create two routes on your server that return only JSON data (no HTML or text)
As for how to fetch and commit this from the JS UI, see https://developer.paypal.com/demo/checkout/#/pattern/server for some demo code.
Alternatively, you could try doing an HTML/JS-only integration (no server) like https://developer.paypal.com/demo/checkout/#/pattern/client

Integration of Amazon Payments with Javascript and PHP - PaymentPlanNotSet

Currently I try to integrate amazon payment.
I want to display the button, created with the function:
OffAmazonPayments.Button("AmazonPayButton", myAmznMerchantID
and after the User has logged in, I want to display the AdressBook Widget and the Payment Widget on the same Page.
The Button and the Widgets are displayed correctly, but when I try to confirm the Payment, I'm getting the Error-Constrains Message:
PaymentPlanNotSet The buyer has not been able to select a Payment
method for the given Order Reference.
But the Payment was selected.
I hope you can help me, to find my failure in this Javascript code:
window.onAmazonLoginReady = function () {
amazon.Login.setClientId(myAmznClientID);
};
window.onAmazonPaymentsReady = function() {
var __accessToken = 0;
var __orderReferenceId = 0;
show_amazon_Button();
function show_amazon_Button() {
OffAmazonPayments.Button("AmazonPayButton", ibuiAmazonPaymentsInfos.ibAmznMerchantID, {
type: "PwA",
color: "Gold",
size: "small", // "medium",
language: "de-DE",
authorization: function () {
loginOptions = { scope: "profile:user_id", popup: true };
authRequest = amazon.Login.authorize(loginOptions, function(response) {
if (response.error) {
//show Error
return;
} else {
__accessToken = response.access_token;
show_Adress_Widget();
}
});
},
onError: function(error) {
//handleError
}
});
}
function show_Adress_Widget() {
new OffAmazonPayments.Widgets.AddressBook({
sellerId: ibuiAmazonPaymentsInfos.ibAmznMerchantID,
onOrderReferenceCreate: function (orderReference) {
__orderReferenceId = orderReference.getAmazonOrderReferenceId();
//do Stuff
},
onAddressSelect: function (orderReference) {
show_Amazon_Wallet();
},
design: {
designMode: 'responsive'
},
onError: function (error) {
//handle Error
}
}).bind("readOnlyAddressBookWidgetDiv");
}
function show_Amazon_Wallet() {
new OffAmazonPayments.Widgets.Wallet({
sellerId: myAmznMerchantID,
onOrderReferenceCreate: function(orderReference) {
//do Stuff
},
design: {
designMode: 'responsive'
},
onPaymentSelect: function(orderReference) {
//activate buy button
},
onError: function(error) {
//handle error
}
}).bind('AmazonWalletWidgetDiv');
}
} //onAmazonPaymentsReady
In PHP I create the OrderReference over:
$params = array(
'order_reference_id' => $orderReferenceId,
'amount' => $amount,
'seller_order_id' => $buchungsKopf->getBuchung_nr(),
);
$responseObject = $client->setOrderReferenceDetails($params);
And even if I had selected a payment method before, I'm getting the "PaymentPlanNotSet" in the responseObject.
Same error, when I try to confirm the orderReference
$responseObject2 = $client->confirmOrderReference($params);
Before I had integrate the AdressWidget, I was able to do the payment.
Can you see what I'm doing wrong?
It seems I have found my failure.
When I want to display both Widgets (Adress and Wallet) on the same page, then I can not use the onOrderReferenceCreate-Method in the OffAmazonPayments.Widget.Wallet.
It seems like then it create a new order reference wich is not the same as the orderreference created by the AdressBook Widget.
Now I have delete this part of the Wallet Widget and everything seems to work fine.

Braintree Drop-in - Submit form after the user has chosen a payment method

is there a way to automatically submit the form after the user has chosen a payment method with the Braintree Drop-in?
The problem is that the user is asked to choose a payment method, then press Ok, then again Ok, then press the actual Checkout button on my page.
It is a very weird behavior.
Here's the code I use to create the Drop-In.
<script>
var form = document.querySelector('#payment-form');
var nonceInput = document.querySelector('#nonce');
braintree.dropin.create({
authorization: '{{ $client_token }}',
container: '#dropin-container',
paypal: {
flow: 'vault',
currency: 'EUR',
buttonStyle: {
color: 'blue',
shape: 'rect',
size: 'medium'
}
},
card: {
cardholderName: true
}
}, function (err, dropinInstance) {
if (err) {
// Handle any errors that might've occurred when creating Drop-in
console.error(err);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
dropinInstance.requestPaymentMethod(function (err, payload) {
if (err) {
// Handle errors in requesting payment method
return;
}
$.fancybox.open({
src : '#processing-loading',
type : 'inline',
opts : {
toolbar: false,
buttons: false,
smallBtn: false
}
});
// Send payload.nonce to your server
nonceInput.value = payload.nonce;
form.submit();
});
});
});
</script>

jQuery Validate plugin - How to show different error messages based on various conditions

Ok, I know that the first thought here for everyone is to simply create another validation method and message. But here is the deal. We have a form that has a field that is used as Employer Name and Company Name, dependent on what is selected in a dropdown.
What I need to be able to do is when the dropdown shows that they own the company and they didn't fill out the field then it shows one message. If they don't own the company and it is empty then it shows another message.
How would I accomplish this? This is using the latest version of jQuery and the Validate plugin (http://jqueryvalidation.org/).
UPDATE:
I present to you the code that I ended up with after the selected answer below was selected...
http://pastebin.com/iG3Z4BbJ
Thanks and enjoy!
Code In Detail:
/**
* Reference: http://jqueryvalidation.org/rules
*/
$(document).ready(function() {
var rules = {
IncomeSource: 'required',
NetIncome: {
required: true,
usDollar: true,
minDollars: 1
},
//Begin - Fields that don't always show
JobTitle: {
//required: true,
nameInput: true
},
Employer: {
//required: true,
nameInput: true
},
EmployerPhone: {
//required: true,
phoneUS: true
},
BenefitSource: {
//required: true,
nameInput: true
},
//SemiMonthlySpecifics: 'required', //Select one when Semi-Monthly or Monthly are selected
//End - Fields that don't always show
PayFrequency: 'required',
LastPayDate: {
required: true,
pastDate: true,
date: true
},
NextPayDate: {
required: true,
futureDate: true,
date: true
},
DirectDeposit: 'required',
EmploymentLength: 'required',
ActiveMilitary: 'required',
RoutingNumber: {
required: true,
digits: true,
rangelength: [9, 9]
},
AccountNumber: {
required: true,
digits: true,
rangelength: [4, 17]
},
AccountType: 'required'
};
//And field specific (and even validation type specific) error messages
var messages = {
IncomeSource: ss.i18n._t('IncomeSourceRequiredError'),
NetIncome: {
required: ss.i18n._t('NetIncomeRequiredError')
},
//Begin - Fields that don't always show
JobTitle: {
required: ss.i18n._t('JobTitleRequiredError')
},
Employer: {
required: ss.i18n._t('EmployerRequiredError')
},
EmployerPhone: {
required: ss.i18n._t('EmployerPhoneRequiredError')
},
BenefitSource: {
required: ss.i18n._t('BenefitSourceRequiredError')
},
SemiMonthlySpecifics: ss.i18n._t('SemiMonthlySpecificsRequiredError'), //Select one when Semi-Monthly or Monthly are selected
//End - Fields that don't always show
PayFrequency: ss.i18n._t('PayFrequencyRequiredError'),
LastPayDate: {
required: ss.i18n._t('LastPayDateRequiredError')
},
NextPayDate: {
required: ss.i18n._t('NextPayDateRequiredError')
},
DirectDeposit: ss.i18n._t('DirectDepositRequiredError'),
EmploymentLength: ss.i18n._t('EmploymentLengthRequiredError'),
ActiveMilitary: ss.i18n._t('ActiveMilitaryRequiredError'),
RoutingNumber: {
required: ss.i18n._t('RoutingNumberRequiredError')
},
AccountNumber: {
required: ss.i18n._t('AccountNumberRequiredError')
},
AccountType: ss.i18n._t('AccountTypeRequiredError')
};
$('#applicationForm').validate({
//debug: true,
rules: rules,
messages: messages,
errorElement: 'span',
ignore: '.ignore',
onfocusout: function( element, event ) {
$(element).valid();
},
invalidHandler: function(event, validator) {
kclHelpers.openErrorModal(event, validator);
},
errorPlacement: function(error, element) {
var insertLocation = kclHelpers.getInsertLocation(element);
error.appendTo( insertLocation );
},
success: function(label, element) {
element = $(element);
var insertLocation = kclHelpers.getInsertLocation(element);
insertLocation.hide();
kclHelpers.parentShowSuccess(element, '.control-group');
},
//Had to use this for show/hide of errors because error placement doesn't get called on every error.
showErrors: function(errorMap, errorList) {
if (this.numberOfInvalids() > 0) {
//We want to make sure that we show/hide things appropriately on error
$.each(errorList, function(index, item) {
var domElement = item['element'];
var message = item['message'];
var element = $(domElement);
var insertLocation = kclHelpers.getInsertLocation(element);
insertLocation.show();
kclHelpers.parentShowError(element, '.control-group');
});
}
this.defaultShowErrors();
}
});
$('[rel=tooltip]').tooltip();
// When the income source is changed, change the form respectively
$('#IncomeSource').on('change', kclFinancialInfo.incomeSourceChanged);
$('#PayFrequency').on('change', kclFinancialInfo.payFrequencyChanged);
});
/**
* This is where we specify functions only for this form
*/
var kclFinancialInfo = function()
{
return {
incomeSourceChanged: function() {
// Store and convert the income source to lowercase
var val = $(this).val().toLocaleLowerCase();
// Switch on the income source
switch (val) {
// Case for 'benefits'
case 'benefits':
// Do not display the employment section
kclFinancialInfo.toggleEmploymentSection(false);
// Display the benefit source section
kclFinancialInfo.toggleBenefitSource(true);
break;
// Case for 'selfemployment'
case 'selfemployment':
// Display the benefit source section
kclFinancialInfo.toggleBenefitSource(false);
// Display the employment section
kclFinancialInfo.toggleEmploymentSection(true, "Please enter your company's name");
// Call to update the labels for the employment section based on income source of 'selfemployment'
kclFinancialInfo.updateEmploymentSectionLabels('selfemployment');
// Hide the employer phone field
kclFinancialInfo.toggleEmployerPhone(true);
break;
// Case for 'job' and default
case 'job':
default:
// Do not display the benefit source
kclFinancialInfo.toggleBenefitSource(false);
// Display the employment section
kclFinancialInfo.toggleEmploymentSection(true, "Please enter your employer's name");
// Call to update the labels for the employment section based on income source of 'job'
kclFinancialInfo.updateEmploymentSectionLabels('job');
// Do not hide the employer phone field
kclFinancialInfo.toggleEmployerPhone(false);
break;
}
},
payFrequencyChanged: function() {
var val = $(this).val().toLocaleLowerCase();
switch (val) {
case 'semi_monthly':
// Display the Specific SemiMonthly section
kclFinancialInfo.toggleSpecificSemiMonthly(true, val);
case 'monthly':
// Display the Specific SemiMonthly section BUT change the labels
kclFinancialInfo.toggleSpecificSemiMonthly(true, val);
break;
default:
// Do not display the Specific SemiMonthly section
kclFinancialInfo.toggleSpecificSemiMonthly(false);
break;
}
},
toggleSpecificSemiMonthly: function(show, value) {
if (show) {
if (value == 'semimonthly') {
$('#specifics-label-for-SemiMonthlySpecifics_day').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.SEMI_MONTHLY_SPECIFICS_DAY'));
$('#specifics-label-for-SemiMonthlySpecifics_date').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.SEMI_MONTHLY_SPECIFICS_DATE'));
}
else {
$('#specifics-label-for-SemiMonthlySpecifics_day').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.MONTHLY_SPECIFICS_DAY'));
$('#specifics-label-for-SemiMonthlySpecifics_date').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.MONTHLY_SPECIFICS_DATE'));
}
$('#semi-monthly-specifics').show().removeClass('hidden');
$('input[name="SemiMonthlySpecifics"]').rules('add', 'required');
}
else {
kclHelpers.hideMessage('SemiMonthlySpecifics');
$('#semi-monthly-specifics').hide().addClass('hidden');
$('input[name="SemiMonthlySpecifics"]').rules('remove', 'required');
}
},
toggleEmployerPhone: function(hide) {
// If you want to hide the employer phone field
if (hide) {
// Hide the employer phone
$('#employer_phone').hide().addClass('hidden');
$('employer_phone').rules('remove', 'required');
}
// Else (you don't want to hide the employer phone field)
else {
// Display the employer phone field
$('#employer_phone').show().removeClass('hidden');
$('employer_phone').rules('add', 'required');
}
},
toggleBenefitSource: function(show) {
// If you want to show the benefit sources section
if (show) {
// Show the benefit source section
$('#benefit_source').show().removeClass('hidden');
// Since the benefit source section is now visible, make it required
$('#BenefitSource').rules('add', 'required');
/**
* Hide the WorkPhone validation message if its displayed (it remains on the screen if the user
* selects benefits)
*/
kclHelpers.hideMessage('WorkPhone');
}
// Else (you don't want to show the benefit source section, display the default employment section)
else {
// Hide the benefit source section
$('#benefit_source').hide().addClass('hidden');
// Since the benefit source is now hidden, it is no longer required
$('#BenefitSource').rules('remove', 'required');
}
},
toggleEmploymentSection: function(show, employerMessage = '') {
// If you want to show the employment section
if (show) {
// Show the employment section
$('#employment_section').show();
$('#JobTitle').rules('add', 'required');
$('#Employer').rules('add', {
required: true,
messages: {
required: employerMessage
}
});
$('#EmployerPhone').rules('add', 'required');
}
// Else (you don't want to show the employment section)
else {
// Hide the employment section
$('#employment_section').hide();
$('#JobTitle').rules('remove', 'required');
$('#Employer').rules('remove', 'required');
$('#EmployerPhone').rules('remove', 'required');
}
},
updateEmploymentSectionLabels: function(source) {
// Switch on the income source (now lowercase)
switch (source.toLocaleLowerCase()) {
// Case for 'job'
case 'job':
/**
* Make sure the job title and employer labels are correct (this is needed in case the labels
* need to be changed back to default
*/
$('#JobTitle_label').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.JOB_TITLE'));
$('#Employer_label').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.EMPLOYER'));
$('#Employer').attr('placeholder', 'Enter Employer Name');
break;
// Case for 'selfemployment'
case 'selfemployment':
// Change the employer label to correspond to self employment (Employer -> Your Company Name)
$('#Employer_label').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.SELF_EMPLOYER'));
$('#Employer').attr('placeholder', 'Enter Company Name');
break;
}
}
}
}();
var kclHelpers = function()
{
var firstErrorID = '';
var errorCount = 0;
return {
//Expects jQuery element
getInsertLocation: function(element) {
var fieldName = element.attr('name');
if (fieldName == 'Reference_1[Relationship]') {
fieldName = 'Reference_1-Relationship';
}
else if (fieldName == 'Reference_2[Relationship]') {
fieldName = 'Reference_2-Relationship';
}
var insertTo = "#" + fieldName + "-error";
return $(insertTo);
},
//Expects jQuery element and a selector string
parentShowError: function(element, parentSelector) {
var parentElem = element.parents(parentSelector);
if (!parentElem.hasClass('has-error')) {
parentElem.addClass('has-error');
}
parentElem.removeClass('has-success');
},
//Expects jQuery element and a selector string
parentShowSuccess: function(element, parentSelector) {
var parentElem = element.parents(parentSelector);
if (!parentElem.hasClass('has-success')) {
parentElem.addClass('has-success');
}
parentElem.removeClass('has-error');
},
hideMessage: function(fieldName) {
if (fieldName == 'CreatePassword') {
// Clear the Create-Password error message as well as the Confirm-Password error message
$('#ConfirmPassword-error').hide();
}
if (fieldName == 'CellPhone') {
// Clear the Cell-Phone error message as well as the Home-Phone error message
$('#HomePhone-error').hide();
}
/**
* Find the id in the form styling file corresponding to field we wish to "clear"
* And set its "display" value to "none", effectively deleting it
* This is for the desktop version
*/
$("#" + fieldName + "-error").hide();
},
openErrorModal: function(event, validator) {
var errorCnt = validator.numberOfInvalids();
var errors = '';
var hasSetErrorID = false;
kclHelpers.errorCount = errorCnt;
if (errorCnt) {
var message = "";
for (var i in validator.errorMap) {
if (!hasSetErrorID) {
hasSetErrorID = true;
kclHelpers.firstErrorID = i;
}
var str = i;
var label = '';
if (i == 'AgreeTerms') {
label = 'Website terms';
}
else if (i == 'ContactTerms') {
label = 'Contact terms';
}
else if (i == 'HomePhone') {
label = 'Home Phone';
}
else if (i == 'RoutingNumber') {
label = 'Routing Number';
}
else if (i == 'AccountNumber') {
label = 'Account Number';
}
else if (i == 'SemiMonthlySpecifics') {
label = 'Pay Frequency Specifics';
}
else if (/Reference_1/i.test(str)) {
label = 'Reference 1 ' + $("label[for='" + i + "']").text();
}
else if (/Reference_2/i.test(str)) {
label = 'Reference 2 ' + $("label[for='" + i + "']").text();
}
else {
label = $("label[for='" + i + "']").text();
}
errors += '<li>' + label + ': ' + validator.errorMap[i] + '</li>';
}
message += '<ol>' + errors + '</ol>';
$('#form-error-modal .modal-body .error-count').text(errorCnt);
$('#form-error-modal ul.error-list').html(message);
$('#form-error-modal').modal('show');
}
}
}
}();
Here's a much cleaner (and probably the correct) way
messages: {
RoutingNumber: {
required:"Message1",
digits: "Message2",
rangelength: "Message 3"
}
}
For more validation methods: List of built in validation methods
Use the .rules('add') method to dynamically change the message on change of the select. Then use the .valid() method to trigger a new test on the field in order to instantly update the message.
$(document).ready(function () {
$('#myform').validate({
rules: {
type: {
required: true
},
theName: {
required: true
}
}
});
$('select[name="type"]').on('change', function () {
var theMessage,
theType = $(this).val();
if (theType == 'employer') {
theMessage = "Required Message 1";
} else if (theType == 'company') {
theMessage = "Required Message 2";
} else {
theMessage = "This field is required.";
}
// dynamically change the message
$('input[name="theName"]').rules('add', {
messages: {
required: theMessage
}
});
// trigger immediate validation to update message
$('input[name="theName"]').valid();
});
});
Working DEMO: http://jsfiddle.net/CLFY9/

jTable Conditional show\hide edit and delete buttons based on owner of data

Im using jTable to display CDs info and a child table to show reviews of that CD. I want to be able to only show the edit\delete buttons on the rows for the user that is logged in. I have been trying to follow the suggestions made on: https://github.com/hikalkan/jtable/issues/113
https://github.com/hikalkan/jtable/issues/893
https://github.com/hikalkan/jtable/issues/620
Can honestly say im not having much luck with any of these examples. We had been told to include some jquery in our assignment so I chose to go with using it for my table data. Im wishing now id just done something very basic!
Working jTable without condition:
display: function (reviewData) {
//Create an image that will be used to open child table
var $img = $('<img class="child-opener-image" src="/Content/images/Misc/list_metro.png" title="List Reviews" />');
//Open child table when user clicks the image
$img.click(function () {
$('#ReviewTableContainer').jtable('openChildTable',
$img.closest('tr'),
{
title: "Your reviews on this album",
actions: {
listAction: 'childReviewActions.php?action=list&ID=' + reviewData.record.CDID,
deleteAction: 'childReviewActions.php?action=delete&ID=' + reviewData.record.CDID,
updateAction: 'childReviewActions.php?action=update&ID=' + reviewData.record.CDID
},
fields: {
userID: {
key: true,
create: false,
edit: false,
list: false
},
userName: {
title: 'User',
edit: false,
width: '20%'
},
reviewDate: {
title: 'Review date',
width: '20%',
type: 'date',
edit: false,
displayFormat: 'dd-mm-yy'
},
reviewText: {
title: 'Review',
type: 'textarea',
width: '40%'
}
},
Issue 620 attempt:
actions: {
listAction: 'childReviewActions.php?action=list&ID=' + reviewData.record.CDID,
#if (reviewData.record.userID == <?php echo mysql_real_escape_string($_SESSION['ID']);?>)
{
deleteAction: 'childReviewActions.php?action=delete&ID=' + reviewData.record.CDID,
updateAction: 'childReviewActions.php?action=update&ID=' + reviewData.record.CDID
}
},
This way gives me compile error: invalid property id on the IF statement.
If I take out the # in the if statement I get: missing : after property id.
Issue 113 & 893 attempt:
actions: {
listAction: {
url:'http://localhost/childReviewActions.php?action=list&ID=' + reviewData.record.CDID
//updateAction: {
//url:'childReviewActions.php?action=update&ID=' + reviewData.record.CDID,
//enabled: function (data) {
//return data.record.userID = <?php echo mysql_real_escape_string($_SESSION['ID']);?>;
//}
//}
},
On this I couldnt even get it to list the contents of the child table. It keeps coming back with 404 not found error: The requested url /[object object] was not found on this server. Has anyone any ideas how to get these examples working on have a different example of how to get the table to enable\enable the edit, update buttons? This is all new to me so I apologise now
rowInserted: function (event, data) {
//After child row loads. Check if the review belongs to the member logged in. If not remove the edit/delete buttons
if (data.record.userID != $user) {
data.row.find('.jtable-edit-command-button').hide();
data.row.find('.jtable-delete-command-button').hide();
}
else{
//If a review record does belong to the user set variable to true so the add new review link can be hidden after all records have been loaded
$memberReviewExists = true;
//Also needed here for when a new record is inserted
$(".jtable-add-record").hide();
}
},
recordsLoaded: function (event, data) {
if (typeof $memberReviewExists != 'undefined' && $memberReviewExists == true){
$(".jtable-add-record").hide();
$memberReviewExists = null;
}
else {
//No review currently exists for this user so show the Add review link $(".jtable-add-record").show();
}
},
recordDeleted: function (event, data) {
//User has deleted their review. Re-show the add new review link
$(".jtable-add-record").show();
}
The following worked for me. It hides the edit/delete button on rows where the current user is not the authorized user. Note: I added a column for authorizedUser in the mysql table and use that to know if the user is allowed or not.
rowInserted: function(event, data){
var $currentUser='<?php echo $_SESSION['email']?>';
if (data.record.authorizedUser != $currentUser) {
data.row.find('.jtable-edit-command-button').hide();
data.row.find('.jtable-delete-command-button').hide();
}
},
#Toni Your code contains asp.net code too. # is ASP.NET Directive.

Categories

Resources