Jquery The name '' is does not exists in the current context - javascript

Although there are several same questions, I'm very curious regarding this specific case.
jQuery(document).ready(function () {
if ($('#msg').val() != '' && $('#msgSuccess').val() == 'true') {
var msg = $('#msg').val();
var t = $('#msg').val().toString();
toastr.success("#_localizer[t]");
}
});
variable t has some message which represents the key for my localization file.
I have issue to pass that variable (string) to my mvc _localizer.
Where I go wrong with this?
If I add simple console.log(t) it works. So Im guessing that is the localizer is a problem.
I'm using #inject IViewLocalizer _localizer from AspNetCore.Mvc.Localization

Related

'checked' with if statement does not work properly

Hi guys i am making calculator app and i have got a problem.
I made 3 radio buttons and want them to be checked with 'if statement' in JS file. It just does not work at all because 'main' does not get any class when input2 or 3 is clicked. Only the first one makes 'main' getting it but thats because of input1.checked defaultly set to true. Can anyone help me, pls?
Here is the link to the project on my github:
https://github.com/Adrian397/frontEndMentorChallenges/tree/master/calculator-app-main
Here is live site of it: https://adrian397.github.io/frontEndMentorChallenges/calculator-app-main/index.html
js file
html file
Really liked your idea with different themes.
Coming to your query.
Looks like you have been using const for the main variable. Hence you won't be able to change it.
It would help if you can change the variables to var or let.
Note : Always use const when you are sure that you are not going to change that variable.
Also, its a great habit if you can use :
if(document.getElementById('input1').checked) {
document.getElementById("main").innerHTML
= <Your code goes here>
}
This simplifies the process and keeps the source clean for one Page applications.
Hope this helps. May the source be with you !
Before all, at the first line of your js code you are declaring let main= document.querySelector('main');
This cannot works there because a variable declared as let can be visible only in the function where it is declared so
It's not in the scope of your function declared later (Not visible to it)
then you are declarig input as const and it could give some problem because a constant cannot update so the state checked should be always the same
your code corrected should be this
document.addEventListener("DOMContentLoaded", ()=>{
let main = document.getElementById("main");
let firstInput = document.getElementById("input1");
let secondInput = document.getElementById("input2");
let thirdInput = document.getElementById("input3");
if(firstInput.checked == true){
main.classList.add('dark');
}else {
main.classList.remove('dark');
}
});
Just add the other 'if' like this above.
Also give an id to the html element main to get it from id
I got help on another post so here im pasting corectly working code:
let input1 = document.getElementById("input1");
let input2 = document.getElementById("input2");
let input3 = document.getElementById("input3");
let main = document.getElementById("main");
input1.checked = true;
function setColorTheme() {
if (input1.checked == true) {
main.classList.add("dark");
} else {
main.classList.remove("dark");
}
if (input2.checked == true) {
main.classList.add("light");
} else {
main.classList.remove("light");
}
if (input3.checked == true) {
main.classList.add("saturated");
} else {
main.classList.remove("saturated");
}
}
setColorTheme();
document.querySelectorAll('input[name="theme"]').forEach((e) => {
e.addEventListener("change", setColorTheme);
});
The problem was solved by adding these lines and making variables declarations using 'let':
document.querySelectorAll('input[name="theme"]').forEach((e) => {
e.addEventListener("change", setColorTheme);
});

Javascript data mapping

Can someone explain to me how can I implement in a clean way a solution to get a status (string) from combining two other ones?
I need to declare a function which takes two params (two strings) and needs to return another one based on the combination of those two strings.
For ex:
carStatus(status, secondaryStatus) => string
where secondaryStatus can have multiple options.
I'm thinking using an if/else if statement which returns a third status which I need.
For ex when status is 'OPEN' and secondaryStatus is 'payment1' or 'payment2' or 'payment3', the function must return a new string (status) like 'CONFIRMED'.
So, an example of how I'm thinking to implement at this moment would be something like this:
carStatus = (status, secondaryStatus) => {
if(status === 'OPEN' && (secondaryStatus === 'payment1' || 'payment2' || 'payment3')){
return 'CONFIRMED';
} else if(status === 'CANCELLED' && (secondaryStatus === 'payment4' || 'payment5' || 'payment6')){
return 'REMOVED';
} else if(status === 'REVIEW' && (secondaryStatus === 'payment2' || 'payment5' || 'payment5')){
return 'CHECKED';
}
}
<div>carStatus('OPEN', 'payment1')</div>
In div must be rendered 'CONFIRMED'.
In my implementation, I'll have to write I think other 5 else if statements.. so maybe there is a cleaner way to implement this.
My project is written in React, but I'm thinking to put this function in utils folder. Perhaps a solution written in React could be more clean? I don't know.
Any help will be appreciated.
You can probably use a lookup object for the various options. Since criteria given is very vague following is a very basic example
const carStatus = (carState, carSecondaryState) => {
const secondaries = {
ORDERED: 'CLIENT'
}
return `${secondaries[carSecondaryState]}_${carState}`
}
console.log(carStatus('NEW', 'ORDERED'))

TypeError: Cannot read property 'getValue' of null at welcomeAlert

I'm new in CRM.
I need just on the OnLoad event of the page, show a JavaScript alert message: "Welcome 'Account Name'".
This is my simple code:
function welcomeAlert()
{
var userName = Xrm.Page.getAttribute("name").getValue();
if(userName !== null)
{
alert("Welcome " + userName + "!");
}
}
But I'm getting error message onLoad: TypeError: Cannot read property 'getValue' of null at welcomeAlert.
If my code looking like code below everything works fine.
function welcomeAlert()
{
alert("Welcome ");
}
Somebody can help? Maybe the attribute name is not ok. But I don't know how to check it.
Verify the attribute name to make sure its in the form
If the field is a custom attribute then it will be having publisher name prefix ex. new_name
If the field is added in header/footer sections or BPF stages then it will be renamed like header_name
Check if it’s hidden or added multiple times in the form & use browser developer toolbar to inspect the DOM
You can validate like if(formContext.getAttribute("name") != null before accessing getValue()
Depending on your version of CRM, Xrm.Page may be deprecated. Refer to deprecation page
The correct way of doing this is to use the executionContext object which is a parameter that can be passed to your methods by CRM. Microsoft provides an an example of how to do that here but the steps are:
Update your method to include a new parameter: e.g. function welcomeAlert(executionContext)
Use executionContext to retrieve the formContext: e.g. var formContext = executionContext.getFormContext()
Use formContext as a substitute for Xrm.Page: e.g. var userName = formContext.getAttribute("name").getValue();
When you register this function in CRM, you need to be sure to check the Pass execution context as first parameter option otherwise CRM will not pass the executionContext to your function
Putting it all together, your method should look like this:
function welcomeAlert(executionContext)
{
var formContext = executionContext.getFormContext();
var userName = formContext.getAttribute("name").getValue();
if(userName !== null)
{
alert("Welcome " + userName + "!");
}
}
I solved my problem!
I read this on docs.microsoft, so I thought that the attribute for Account Name is "name". var nameValue = Xrm.Page.getAttribute("name").getValue();
Assigns the value of the Account Name field to the nameValue variable.
The right attribute for Account Name is "parentcustomerid". This code works for me.
function welcomeAlert()
{
var userName = Xrm.Page.getAttribute("parentcustomerid").getValue()[0].name;
if(userName !== null)
{
alert("Welcome " + userName + "!");
}
}
Thank you all for response.

getting sessionid with javascript

Under the headline:
Finding the session id with javascript in the browser
from this link:
Link to Autopilot
it says that I with the line of code can capture the Autopilot session id.
var sessionId = AutopilotAnywhere.sessionId;
I tried to set the line of code in the console, but I get undefined:
I am not quite sure how to use this line of code. Can anybody see how I use the line of code?
Try it:
function getJSessionId(){
var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
if(jsId != null) {
if (jsId instanceof Array)
jsId = jsId[0].substring(11);
else
jsId = jsId.substring(11);
}
return jsId;
}

Breeze Partial initializer

I have a Single Page Application that is working pretty well so far but I have run into an issue I am unable to figure out. I am using breeze to populate a list of projects to be displayed in a table. There is way more info than what I actually need so I am doing a projection on the data. I want to add a knockout computed onto the entity. So to accomplish this I registered and entity constructor like so...
metadataStore.registerEntityTypeCtor(entityNames.project, function () { this.isPartial = false; }, initializeProject);
The initializeProject function uses some of the values in the project to determine what the values should be for the computed. For example if the Project.Type == "P" then the rowClass should = "Red".
The problem I am having is that all the properties of Project are null except for the ProjNum which happens to be the key. I believe the issue is because I am doing the projection because I have registered other initializers for other types and they work just fine. Is there a way to make this work?
EDIT: I thought I would just add a little more detail for clarification. The values of all the properties are set to knockout observables, when I interrogate the properties using the javascript debugger in Chrome the _latestValue of any of the properties is null. The only property that is set is the ProjNum which is also the entity key.
EDIT2: Here is the client side code that does the projection
var getProjectPartials = function (projectObservable, username, forceRemote) {
var p1 = new breeze.Predicate("ProjManager", "==", username);
var p2 = new breeze.Predicate("ApprovalStatus", "!=", "X");
var p3 = new breeze.Predicate("ApprovalStatus", "!=", "C");
var select = 'ProjNum,Title,Type,ApprovalStatus,CurrentStep,StartDate,ProjTargetDate,CurTargDate';
var isQaUser = cookies.getCookie("IsQaUser");
if (isQaUser == "True") {
p1 = new breeze.Predicate("QAManager", "==", username);
select = select + ',QAManager';
} else {
select = select + ',ProjManager';
}
var query = entityQuery
.from('Projects')
.where(p1.and(p2).and(p3))
.select(select);
if (!forceRemote) {
var p = getLocal(query);
if (p.length > 1) {
projectObservable(p);
return Q.resolve();
}
}
return manager.executeQuery(query).then(querySucceeded).fail(queryFailed);
function querySucceeded(data) {
var list = partialMapper.mapDtosToEntities(
manager,
data.results,
model.entityNames.project,
'ProjNum'
);
if (projectObservable) {
projectObservable(list);
}
log('Retrieved projects using breeze', data, true);
}
};
and the code for the partialMapper.mapDtosToEntities function.
var defaultExtension = { isPartial: true };
function mapDtosToEntities(manager,dtos,entityName,keyName,extendWith) {
return dtos.map(dtoToEntityMapper);
function dtoToEntityMapper(dto) {
var keyValue = dto[keyName];
var entity = manager.getEntityByKey(entityName, keyValue);
if (!entity) {
extendWith = $.extend({}, extendWith || defaultExtension);
extendWith[keyName] = keyValue;
entity = manager.createEntity(entityName, extendWith);
}
mapToEntity(entity, dto);
entity.entityAspect.setUnchanged();
return entity;
}
function mapToEntity(entity, dto) {
for (var prop in dto) {
if (dto.hasOwnProperty(prop)) {
entity[prop](dto[prop]);
}
}
return entity;
}
}
EDIT3: Looks like it was my mistake. I found the error when I looked closer at initializeProject. Below is what the function looked like before i fixed it.
function initializeProject(project) {
project.rowClass = ko.computed(function() {
if (project.Type == "R") {
return "project-list-item info";
} else if (project.Type == "P") {
return "project-list-item error";
}
return "project-list-item";
});
}
the issue was with project.Type I should have used project.Type() since it is an observable. It is a silly mistake that I have made too many times since starting this project.
EDIT4: Inside initializeProject some parts are working and others aren't. When I try to access project.ProjTargetDate() I get null, same with project.StartDate(). Because of the Null value I get an error thrown from the moment library as I am working with these dates to determine when a project is late. I tried removing the select from the client query and the call to the partial entity mapper and when I did that everything worked fine.
You seem to be getting closer. I think a few more guard clauses in your initializeProject method would help and, when working with Knockout, one is constantly battling the issue of parentheses.
Btw, I highly recommend the Knockout Context Debugger plugin for Chrome for diagnosing binding problems.
Try toType()
You're working very hard with your DTO mapping, following along with John's code from his course. Since then there's a new way to get projection data into an entity: add toType(...) to the end of the query like this:
var query = entityQuery
.from('Projects')
.where(p1.and(p2).and(p3))
.select(select)
.toType('Project'); // cast to Project
It won't solve everything but you may be able to do away with the dto mapping.
Consider DTOs on the server
I should have pointed this out first. If you're always cutting this data down to size, why not define the client-facing model to suit your client. Create DTO classes of the right shape(s) and project into them on the server before sending data over the wire.
You can also build metadata to match those DTOs so that Project on the client has exactly the properties it should have there ... and no more.
I'm writing about this now. Should have a page on it in a week or so.

Categories

Resources