I have a ZenDesk form and they have recommended me a javascript code to solve a problem that I have to edit the fields of the form and make them read-only, the problem is that I can't use normal javascript in angular9, the code from the documentation is this:
<script type="text/javascript">
zE('webWidget', 'prefill', {
name: {
value: 'isamu',
readOnly: true // optional
},
email: {
value: 'isamu#voltron.com',
readOnly: true // optional
},
phone: {
value: '61431909749',
readOnly: true // optional
}
});
</script>
I tried states solutions and they did not work for me
this.s.type = "text/javascript";
this.s.id = "ze-snippet";
this.s.src = "XXX";
this.s.text = "";
this.renderer2.appendChild(this.document.body, this.s);
this.zE('webWidget', 'prefill', {
name: {
value: 'isamu',
readOnly: true // optional
},
email: {
value: 'isamu#voltron.com',
readOnly: true // optional
}
});
window["zE"] = {
webWidget: {
prefill: {
name: {
value: 'isamu',
readOnly: true // optional
},
email: {
value: 'isamu#voltron.com',
readOnly: true // optional
}
}
}
};
What could I do with this problem?
Related
I have a array of object
const formFields = {
firstName: {
value: '',
label: 'FirstName',
type: 'text',
placeHolder: 'Enter Firstname',
helperText: '',
required: false,
error: false
},
lastName: {
value: '',
label: 'LastName',
type: 'text',
placeHolder: 'Enter LastName',
helperText: '',
required: false,
error: false
},
emailID: {
value: 'sfas',
label: 'emailID',
type: 'email',
placeHolder: 'Enter Email ID',
helperText: '',
required: true,
error: false
},
password: {
value: '',
label: 'password',
type: 'password',
placeHolder: 'Enter password',
helperText: '',
required: true,
error: false
},
confirmPassword: {
value: '',
label: 'confirmPassword',
type: 'password',
placeHolder: 'Enter Confirm Password',
helperText: '',
required: true,
error: false
}
}
const [inpValues, setInpValues] = useState(formFields)
Filter and Update
I am trying to filter the object by values where required === true and value.length === 0
and update the filtered array values like helperText = "Enter the " + label and error = true
const validate = () => {
const requiredFields = Object.values(inpValues).filter((fields) => {
if (fields.required === true && fields.value.length === 0) {
//How to setInpValues
//setInpValues(...inpValues, fields: { fields.helperText = "Enter the " + fields.label})
//fields.error = true
}
})
}
<MyButton color="primary" handleOnClick={validate} text="SIGN UP"></MyButton>
The validate function should be, this will also take care of reverting the error back in case of validity.
const validate = () => {
let newValues={...inpValues}
const requiredFields = Object.keys(newValues).forEach((key) => {
let field=newValues[key];
if (field.required === true && field.value.length === 0) {
field.helperText=`Enter the ${field.label}`;
field.error = true;
newValues[key]= field;
}else{
newValues[key].error=false;
newValues[key].helperText='';
}
})
setInpValues(newValues);
}
The array filter callback function expects you to return a boolean that says if the current value should be filtered out or not. I think something like
const validate = () => {
const requiredFields = Object.values(inpValues).filter((fields) => {
if (fields.required === true && fields.value.length === 0) {
return true;
}
return false;
})
setInpValues(requiredFields)
}
this would solve it. In this example you first filter the input values and when they're filtered, you set them to the state. This sets inputValues to be all the required fields, every time you click.
Currently I'm looking to validate new created row before saving changes,
schema is not working to enforce the rules on the created row.
I need to let the user know what fields are required if he tried to save with an error message.
This example has already custom validation ,you can see it in the schema ,the problem it's not forcing validation before submitting to the server.
var gResult = new kendo.data.DataSource({
read:,
update:,
create:,
schema: {
model: {
id: "Id",
fields: {
Id: { type: 'number' },
Color: { type: 'string', defaultValue: "#000" },
Name: {type: 'string', validation: { required: true } },
Address1: { validation: { required: true } },
City: { validation: { required: true } },
Country: { validation: { required: true }, defaultValue: "Deutchland" },
PostalCode: { type: 'number', validation: { required: true } },
Emails: {
type: 'string',
validation: {
required: { message: "Email ID Required." },
validateEmailFormat: function (input) {
if (input.attr("data-bind") == "value:Email") {
input.attr("data-validateEmailFormat-msg", "Email format invalid.");
return checkEmail(input.val());
}
return true;
}
}
}
}
}
});
$("#gridResult").kendoGrid({
columns: GridColumns.Columns,
dataSource: gResult,
navigatable: true,
sortable: true,
height: 1000,
filterable: true,
pageable: GridProp.Pageable,
editable: true, toolbar: ["create", "save"] });
Currently, I'm writing an app on Node.js 5.2.0 on a Linux box with Redis and Caminte. When trying to add different prototype methods to a database object, the context of what this refers to constantly shifts within our reference. After calling push in modelRules.js, this shifts types. I was looking for some assistance with:
How to consistently reference the instantiation of a specific module (function that accepts a schema object) outside of the module itself. I want to tack on prototype functions such as addModelBelongsTo to a User object, and sadly my function simply seems to break when referencing the internal modifiable data members within the class.
The proper organization of the prototype accessors. Is there a specific style that should be used when referencing the insides of the instantiations of these classes?
Why the instantiation of the class User persists data across multiple instantiations of the class? For self[restructuredModelName] (type of array), whenever I call this method on one instantiation, another instantiation of the other object already contains the data of the first instantiation. This should not be happening.
User.js
module.exports = function (schema) {
const IBANVerificationStatusSymbol = Symbol('IBANVerificationStatus');
const relationalMapper = require('./../relationalMapper');
const userObj = {
id: { type: schema.Number },
firstName: { type: schema.String },
lastName: { type: schema.String },
IBAN: { type: schema.String, unique: true },
IBANVerified: { type: schema.Boolean, default: false },
IBANVerificationCode: { type: schema.String },
BIC: { type: schema.String },
email: { type: schema.String, index: true, unique: true },
password: { type: schema.String },
status: { type: schema.Number, default: 0 },
profilePicture: { type: schema.String },
phone: { type: schema.String, index: true, unique: true },
accessToken: { type: schema.String },
prefix: { type: schema.String, default: '+31' },
updated: { type: schema.Date, default: Date.now() },
created: { type: schema.Date, default: Date.now() },
lastAccessedFeed: { type: schema.Date },
street: { type: schema.String },
streetNumber: { type: schema.String },
postalCode: { type: schema.String },
city: { type: schema.String },
country: { type: schema.String },
FCR: { type: schema.Number, default: 0 },
};
// There's GOTTA be a way to typecheck at compilation
const associationMap = {
Activity: { belongsTo: 'Activity', hasMany: 'activities' },
Client: { belongsTo: null, hasMany: 'clients' },
Group: { belongsTo: 'Group', hasMany: 'groups' },
Mandate: { belongsTo: null, hasMany: 'mandates' },
Transaction: { belongsTo: null, hasMany: 'transactions' },
Update: { belongsTo: null, hasMany: 'updates' },
Reaction: { belongsTo: null, hasMany: 'reactions' },
};
relationalMapper.createRelations(associationMap, userObj, schema);
const User = schema.define('user', userObj, {
});
const setId = function (self, models) {
// self.addClients(1);
};
User.hooks = {
afterInitialize: [setId],
};
User.prototype.obj = userObj;
User.associationMap = associationMap;
User.prototype.associationMap = associationMap;
return User;
};
modelRules.js:
function addModelBelongsTo(modelName, models, modelObjKey, modelRelated) {
const restructuredModelName = `memberOf${modelName}`;
const restructuredModelNameCamel = `addMemberOf${modelName}`;
const currentModels = models;
currentModels[modelObjKey].prototype[restructuredModelNameCamel] = function(modelId) {
const self = this;
return new Promise((resolve, reject) => {
if (self[restructuredModelName].indexOf(modelId) <= -1) {
modelRelated.exists(modelId, function(err, exists) {
if (err || !exists) { reject(new Error(err || 'Doesnt exist')); }
console.log(`This:${self}\nrestructuredModelName:${JSON.stringify(self[restructuredModelName])}`);
self[restructuredModelName].push(modelId);
console.log(`This:${self}\nrestructuredModelName:${restructuredModelName}`);
self.save((saveErr) => {
saveErr ? reject(new Error(saveErr)) : resolve(self);
});
});
} else {
reject(new Error(''));
}
});
};
}
I have this data structure of credit card types.
It would be nice to make the hasTransFee more efficient. If I started adding storecards etc to this list it could get quite big so the faster it works the better.
Anyone have any suggestions?
$scope.creditCards = [
{ name: 'VISA DEBIT/DELTA', value: 'DEL', transactionFee: false},
{ name: 'VISA CREDIT', value: 'VIS', transactionFee: true },
{ name: 'MASTERCARD CREDIT', value: 'MSC', transactionFee: true },
{ name: 'MASTERCARD DEBIT', value: 'MCD', transactionFee: false },
{ name: 'MAESTRO', value: 'MAE', transactionFee: false },
{ name: 'SWITCH', value: 'SWI', transactionFee: false },
{ name: 'VISA ELECTRON', value: 'ELC', transactionFee: false },
{ name: 'SOLO', value: 'SOL', transactionFee: false }
];
var hasTransFee = function(cardType)
{
for (var i=0; i < $scope.creditCards.length; i++) {
if($scope.creditCards[i].value==cardType && $scope.creditCards[i].transactionFee == true){
return true;
}
}
return false;
}
It seems that value is a unique identifier, if that's the case you could store the "credit cards" in an object instead, like this:
$scope.creditCards = {
'DEL': { name: 'VISA DEBIT/DELTA', transactionFee: false},
'VIS': { name: 'VISA CREDIT', transactionFee: true },
'MSC': { name: 'MASTERCARD CREDIT', transactionFee: true }
};
And then you don't even need a function for checking if the Credit Card has a transactionFee, if you still want to have a function, that function would look like this:
var hasTransFee = function(cardType){
return $scope.creditCards[cardType].transactionFee;
}
Side-note: This is better suited for CodeReview
Try this:
var hasTransFee = function(cardType)
{
var thecard;
$scope.creditCards.some(function(item) {
return item.value == cardType && (thecard = item);
});
return thecard && thecard.transactionFee;
};
This will only iterate as far as it needs to in order to find the card with the right type, and no further (your original code will continue to scan the whole array if the card is found but has no fee).
Important: Only ONE = sign in && thecard = item. It is deliberately an assignment, required to make the final return work.
But it isn't firing when I hit submit. It submits but doesn't do anything. Any ideas? The alert doesn't even get called :(
The page I'm doing this on, is my Checkout page on:
http://rsatestamls.kaliocommerce.com
(Need a product in your cart to proceed to checkout)
My Javascript code is:
<script>
$(document).ready(function () {
$("#Method input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$('input[type=checkbox][id=OnAccount]').prop('value', 'True')
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
} else {
$('input[type=checkbox][id=OnAccount]').val('No');
}
});
$("#CheckoutOptions input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
});
$("#CheckOut").submit(function (event) {
alert("Handler for .submit() called.");
jQuery.validator.setDefaults({
debug: false,
success: "valid"
});
$("#CheckOut").validate({
rules: {
FirstName: {
required: true
},
LastName: {
required: true
},
Email: {
required: true,
email: true
},
Phone: {
required: true,
digits: true
},
Address1: {
required: true
},
City: {
required: true
},
PostalCode: {
required: true,
digits: true
},
Country: {
required: true
},
State: {
required: true
},
pwd: {
required: true
},
pwd_confirm: {
required: true
},
FName_SHIP: {
required: true
},
LName_Ship: {
required: true
},
Phone_Ship: {
required: true,
digits: true
},
Address1_Ship: {
required: true
},
City_Ship: {
required: true
},
PostalCode_SHIP: {
required: true,
digits: true
},
COUNTRY_SHIP: {
required: true
},
State_SHIP: {
required: true
},
NameOnCard: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CreditCardType: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardNumber: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardExpMonth: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardExpYear: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CVC: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
customernumber: {
required: {
depends: function (element) {
return $("#OnAccount").is(":checked");
}
}
}
}
});
});
populateCartTotal();
</script>
Your submit handler isn't in your $(document).ready block, but should be. The handler is never getting attached.
In fact, you shouldn't use a submit handler at all, here. Just put your validate call in the ready block. See the demo here: http://jquery.bassistance.de/validate/demo/
<script>
$(document).ready(function () {
$("#Method input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$('input[type=checkbox][id=OnAccount]').prop('value', 'True')
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
} else {
$('input[type=checkbox][id=OnAccount]').val('No');
}
});
$("#CheckoutOptions input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
// move this stuff to here
jQuery.validator.setDefaults({
debug: false,
success: "valid"
});
$("#CheckOut").validate({
rules: {
// all those rules here
}
});
});
populateCartTotal();
As an addendum to Ed's answer, I would also recommend setting up your validation scheme outside of the submit() handler.