CRM 2015 read "dirty" value from unsaved form - javascript

I'm creating new account record. The easiest way is to fill account id (vat number or something similar) and push button. Button run some javascript. Javascript read value of account id and fill the rest (call some external ws and fill account name, address and so on).
But I need to read this unsaved account id. Standard
Xrm.Page.getAttribute("accId").getValue();
can read only saved values.
Via debugger I found the right value, so I wrote simple function, which returns it.
Here it is:
function getDirtyValue(attName) {
var control = Xrm.Page.ui.controls.get(attlName);
if (control != null && control.$1G_1 != null) {
return control.$1G_1.$3V_0;
}
else {
return null;
}
}
It works but is there some official way to get this value?
(language correction welcome)

You could avoid this trick by adding a function, called when the form loads, and sets the value of the field into a global variable. You can access that variable in the on change event of that field.
Keep in mind that Microsoft does not support methods that are not present in the SDK and they might change. So if they change the property you are using, and your code is already in production, you'll end up having some problems.
Hope it helps,
Cheers

Related

How to restart a unended game in the middle? [duplicate]

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.
Here is what I tried:
var clicked = false;
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true; return true;");
if (clicked == true) {
// show hidden fields
} else {
// don't show hidden fields
}
});
Any suggestions on what is wrong with this code?
As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.
There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript
Query string
When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:
<form method="GET">
<input type="hidden" name="clicked" value="true" />
<input type="submit" />
</form>
On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.
To read this data, you can use the following script on page load:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var clicked = getParameterByName('clicked');
(Source)
Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.
In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters
Web Storage
With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.
Here I set the storage on the button click event, but you could also bind it to form submit or anything else.
$('input[type="submit"][value="Search"]').click(function() {
sessionStorage.setItem('clicked', 'true');
});
Then when you load the page, you can check if it's set using this:
var clicked = sessionStorage.getItem('clicked');
Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:
sessionStorage.removeItem('clicked');
If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.
//set
localStorage.setItem('myObject', JSON.stringify(myObject));
//get
var myObject = JSON.parse(localStorage.getItem('myObject'));
Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.
Cookies
An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.
You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.
$('input[type="submit"][value="Search"]').click(function() {
$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});
Then on page load you can read the cookie like this:
var clicked = $.cookie('clicked');
As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.
if(clicked === "true") {
//doYourStuff();
$.cookie('clicked', null);
}
(a non-jQuery way to set/read cookies can be found right here)
I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.
window.name
Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:
window.name = "my value"
It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ clicked: true });
The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.
This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.
Try utilizing $.holdReady() , history
function show() {
return $("form input[type=hidden]")
.replaceWith(function(i, el) {
return "<input type=text>"
});
}
$.holdReady(true);
if (history.state !== null && history.state.clicked === true) {
// show hidden fields
// if `history.state.clicked === true` ,
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// don't show hidden fields
console.log(history);
}
$.holdReady(false);
$(document).ready(function() {
$("input[type=submit][value=Search]")
.on("click", function(e) {
e.preventDefault();
if (history.state === null) {
// do stuff
history.pushState({"clicked":true});
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// do other stuff
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="name" value="" />
<input type="submit" value="Search" />
<input type="hidden" />
<input type="hidden" />
</form>
Using localeStorage or sessionStorage seems to be the best bet.
Intead of saving the clicked variable in the globle scope store it this way:
if(localeStorage.getItem("clicked") === null)
localeStorage.setItem("clicked", "FALSE"); // for the first time
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");
var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";
localeStorage.setItem("clicked", clicked);
if (clicked == "TRUE") {
// show hidden fields
} else {
// don't show hidden fields
}
});
You could try this:
$("input[type='submit'][value='Search']").click(function(){
form.act.value='detailSearch';
clicked = true;
return true;
});

how to save state of the page when refreshing? (HTML, JS)

(DISCLAIMER: I'm new to coding so my code probably isn't optimal. If you know a better way to do it, feel free to leave it in the comments )
Most of the time I had no idea what I was doing, but with patience and with you guys' help I came up with this:
if (window.localStorage) {
// Create the Key/Value
var cNum = localStorage.getItem("currentNumber");
if (localStorage.currentNumber == undefined) {
localStorage.setItem("currentNumber","0");}
// Variables
resetCount.innerHTML = localStorage.currentNumber;
// Functions
function btnR() {
cNum++;
localStorage.currentNumber = cNum;
resetCount.innerHTML = cNum;}}
else { console.log("No"); }
HTML:
<button id="resetButton" onclick="btnR()">Reset</button>
<p id="resetCount">0</p>
I was creating a button that each time you click on it, it reset the checkboxes, but I also wanted a counter to see how many times they got rested. The problem was that every time I click the button the counter also reset. Now that is solved I can try to apply the same thing for the checkboxes, so they don't reset on refresh either.
Note: I had to put the .SetItem in an if statement cause, even tho the value was in storage it kept setting back the value to zero every time I refreshed the page. This was the way I found to stop that.
You either need to set up a back end to send data to and save the information you want to keep stored, or save data in localStorage.
Just know it is not the best practice to save sensitive info in localStorage (as they can be compromised in cross-site scripting attacks).
localStorage.setItem puts a bit of data into localStorage (and that stays there till you clear it) and localStorage.getData extracts it.
This might help get you started on localStorage, but you will have to figure out the function to set the colour to the element you have.
let boxColour = localStorage.getItem("boxColour");
if (boxColour === null) {
setBoxColour("colour");
} else {
setBoxColour(boxColour);
}
function setBoxColour(colour){ localStorage.setItem("colour");}
/* Inside the function you have to get the item and change it's style attribute or add a class to add styles */
Careful with that localStorage data!
You could use LocalStorage.
It saves data in the page to be used after when the page is refreshed or closed and opened later.
Theres a example:
(Unfortunally, it seems to not work in the stackoverflow site, but if you try at your HTML file it will work)
var loadFunc = (elem) => {
console.log("Value saved is: "+ localStorage.getItem("savedValue"));
if(localStorage.getItem("savedValue")){ //checks if value is saved or not
elem.checked = localStorage.getItem("savedValue");
}
}
var clickFunc = (elem) => {
localStorage.setItem("savedValue", elem.checked); //set te value if in localStorage
}
Click the checkbox and the value will be saved.
<input type="checkbox" onload="loadFunc(this)" onclick="clickFunc(this)">

change value of variable in external Javascript file [duplicate]

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.
Here is what I tried:
var clicked = false;
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true; return true;");
if (clicked == true) {
// show hidden fields
} else {
// don't show hidden fields
}
});
Any suggestions on what is wrong with this code?
As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.
There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript
Query string
When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:
<form method="GET">
<input type="hidden" name="clicked" value="true" />
<input type="submit" />
</form>
On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.
To read this data, you can use the following script on page load:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var clicked = getParameterByName('clicked');
(Source)
Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.
In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters
Web Storage
With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.
Here I set the storage on the button click event, but you could also bind it to form submit or anything else.
$('input[type="submit"][value="Search"]').click(function() {
sessionStorage.setItem('clicked', 'true');
});
Then when you load the page, you can check if it's set using this:
var clicked = sessionStorage.getItem('clicked');
Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:
sessionStorage.removeItem('clicked');
If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.
//set
localStorage.setItem('myObject', JSON.stringify(myObject));
//get
var myObject = JSON.parse(localStorage.getItem('myObject'));
Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.
Cookies
An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.
You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.
$('input[type="submit"][value="Search"]').click(function() {
$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});
Then on page load you can read the cookie like this:
var clicked = $.cookie('clicked');
As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.
if(clicked === "true") {
//doYourStuff();
$.cookie('clicked', null);
}
(a non-jQuery way to set/read cookies can be found right here)
I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.
window.name
Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:
window.name = "my value"
It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ clicked: true });
The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.
This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.
Try utilizing $.holdReady() , history
function show() {
return $("form input[type=hidden]")
.replaceWith(function(i, el) {
return "<input type=text>"
});
}
$.holdReady(true);
if (history.state !== null && history.state.clicked === true) {
// show hidden fields
// if `history.state.clicked === true` ,
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// don't show hidden fields
console.log(history);
}
$.holdReady(false);
$(document).ready(function() {
$("input[type=submit][value=Search]")
.on("click", function(e) {
e.preventDefault();
if (history.state === null) {
// do stuff
history.pushState({"clicked":true});
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// do other stuff
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="name" value="" />
<input type="submit" value="Search" />
<input type="hidden" />
<input type="hidden" />
</form>
Using localeStorage or sessionStorage seems to be the best bet.
Intead of saving the clicked variable in the globle scope store it this way:
if(localeStorage.getItem("clicked") === null)
localeStorage.setItem("clicked", "FALSE"); // for the first time
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");
var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";
localeStorage.setItem("clicked", clicked);
if (clicked == "TRUE") {
// show hidden fields
} else {
// don't show hidden fields
}
});
You could try this:
$("input[type='submit'][value='Search']").click(function(){
form.act.value='detailSearch';
clicked = true;
return true;
});

Keeping a user-defined JScript variable after reload?

In my HTML document, a button is displayed, and it's onclick event is to alert the variable countervar. Another button can be used to bring countervar up using countervar++. Countervar is never defined in the JScript document, because I want countervar to stay how it was last defined by a user. Like I expected, countervar was nil after each reload. Saving browser cookies also would not work, because the same variable has to be displayed to each user who views the document. I'm looking into "global variables" for an answer, but no luck. Help?
As suggested in the comments, you can use localStorage to achieve part of what you want:
var counter;
// save to local storage
window.localStorage.setItem("counter", counter);
// you can call this whenever you make changes to the counter variable
// load from local storage
// call it when the page loads
if( window.localStorage.getItem("counter") === null){
counter = 0;
}
else{
counter = parseInt(localStorage.getItem("counter"));
}
This will allow you to save the variable for one user. If you want to share it between users, it can't be done just using client side scripting. You'll have to have some sort of server storage/database.

Textbox Unable to get value of the property 'value': object is null or undefined

This is my first attempt at incorporating javascript into my webapp other than one other canned script.
I have a webform in ASP.net VB. On the form I have a checkbox and when that checkbox is checked I want it to prompt the user for a qty, I then want it to subtract that quantity from a quantity in another textbox filled on form load db query. My taqty is not getting the quantity from txtQtyAcc, with error Unable to get value of property 'value': object is null or undefined. I'm also seeing an error for the calculated quantity haqty variable that it is undefined. I'm not sure what I'm missing. I've checked all the similar questions without finding a solution.
var taqty = document.getElementById('<%= txtQtyAcc.ClientId %>').value;
var rejqty = prompt("Enter Reject Qty", "0");
var haqty = taqty.value - rejqty;
function rQty() {
if (rejqty != null) {
document.getElementById('<%= txtQtyRej.ClientID %>') = rejqty.value.toString;
taqty.value = haqty.value.toString
}
}
I'm calling the script from code behind for the checkbox.checkedchanged event.
ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "rQtyFunction", "rQty();", True)
Use following.
ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "rQtyFunction", "rQty();", True).
Note i have used RegisterStartupScript in place of RegisterClientScriptBlock. If you use former i.e. RegisterStartupScript, it will put all script to end of </form> tag, which mean all input DOM elements will be added by that time and will be accessible, you won't get such errors which you had received till now.
This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.
Whereas RegisterClientScriptBlock adds script to at starting for <form>, so there is fair possibility of error.
Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.
For more info on usage of this refer this link - Difference between RegisterStartupScript and RegisterClientScriptBlock?

Categories

Resources