Button on Form Not going through all JS - javascript

I've added a web resource in the shape of a button onto a form in our CRM online instance. I've been debugging for a while now and I don't understand what I'm missing here.
Below is the web resource (I've omitted the javascript URL for obvious reasons)
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-
BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<button onclick="TriggerNPS()" class=".btn-default">
<i class="glyphicon glyphicon-check"></i>
Send NPS Now
</button>
<script src="Javascript URL" type="text/javascript"></script>
</body>
</html>
Javascript that the URL links to
function TriggerNPS() {
var NoTick = parent.Xrm.Page.getAttribute("ondemandnps").getValue();
if ((NoTick) ==null);
parent.Xrm.Page.getAttribute("ondemandnps").setValue("1");
parent.Xrm.Page.data.entity.save();
return
if ((NoTick) !=null)
parent.Xrm.Page.getAttribute("ondemandnps").setValue("0");
parent.Xrm.Page.data.entity.save();
return;
}
What I'm seeing is that if the field which this is looking at (tick box) contains data, then sure it strips the tic. However if the box is empty. I cannot get the script to add the check. Testing this in the console though the command does work. It runs over the lines and doesn't step out of them, but does nothing.
Any help will be appreciated.

Maybe try this:
function TriggerNPS() {
var NoTick = parent.Xrm.Page.getAttribute("ondemandnps").getValue();
if (NoTick == null) {
parent.Xrm.Page.getAttribute("ondemandnps").setValue(true);
}
else {
parent.Xrm.Page.getAttribute("ondemandnps").setValue(false);
}
parent.Xrm.Page.data.entity.save();
}

Related

How to create an HTML template inside a called HTML Template

So, i've been experimenting with de google apps script lately. So far so good, but i ran into a problem that's drivin me out: I have a button in a spreadsheet that calls a sidebar menu with a function in scripts
macros.gs
function sbCases() {
var Form = HtmlService.createTemplateFromFile("Cases");
var ShowForm = Form.evaluate();
ShowForm.setTitle("ASS-CAD - Cases manager system").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showSidebar(ShowForm);
the html file I call with this function works just fine, but I'd like to call a second form, also trough an html file to manage the spreadsheet data. So i've added this function to the .gs file (and started a new html file):
function NovoCasoMSE(){
var Form = HtmlService.createTemplateFromFile("NewCase");
var ShowForm = Form.evaluate();
ShowForm.setTitle("New Case").setHeight(400).setWidth(1000);
SpreadsheetApp.getUi().showModalDialog(ShowForm, "New Case");
}
but when I try to call it from a button in the first html file, nothing happens at clicking the button (checked the log and the function the button should call isn't being executed.
Follow the code (the html is full of stuff, like the buttons and everything)("btn" is the ID for a button working on the html file):
<script>
document.getElementById("btn").addEventListener("click", NewCase);
function NewCase(){
google.script.run.NewCase()
}
</script>
I'm learning c in college but have very little experience in javascript ou google script, so I'm pretty sure I've done something really wrong. Thanks for any help in advance. :)
You can try something like this:
Run showTSidebar to get things rolling and then click the button.
ag1.gs:
function loadForm() {
var html='<form><input type="text" name="name1"/><input type="button" value="Click" onClick="process(this.parentNode);" /></form>';
return html;
}
function showTSidebar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createTemplateFromFile('ah4').evaluate());
}
function processForm(obj) {
SpreadsheetApp.getUi().alert('name1: ' + obj.name1);
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
ah4.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('sbresrc') ?>
</head>
<body>
<div id="form"></div>
<input type="button" value="Load Form" onClick="loadForm();" />
<?!= include('ah6') ?>
</body>
</html>
ah6.html:
<script>
function loadForm() {
google.script.run
.withSuccessHandler(function(html){
$('#form').html(html);
$('#form').css('display','block');
})
.loadForm();
}
function process(obj) {
google.script.run.processForm(obj);
}
</script>
sbresrc.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
animation:

"cannot read property 'innerHTML' of null" error

I am getting the error "cannot read property'innerHTML' of null" at line 11 in the file letterbyletter.js. Its code is this:
function printLetterByLetter(destination, message, speed){
let h = 0;
var interval = setInterval(function(){
if (h===0) {
stop=false
}
if (h > message.length||(stop===true&&h!==0)){
clearInterval(interval);
stop=false
}else if (message.charAt(h)!=="<") {
document.getElementById(destination).innerHTML += message.charAt(h);
h++;
}else {
document.getElementById(destination).innerHTML += "<br>"
h+=4
}
}, speed);
}
It is being called here:
function run(num9) {
if (stats[3][1]>enemies[num9].speed) {
let r=Math.ceil(Math.random()*100)
if (r>=50) {
battlechk=false
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox","You escaped from "+enemies[num9].name+"!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"supdateGUI3()\">Confirm</button>"
}else {
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox",enemies[num9].name+" blocks your path! "+enemies[num9].name+" attacks you!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"battle("+num9+")\">Confirm</button>"
}
}else {
let r=Math.ceil(Math.random()*100)
if (r>=90) {
battlechk=false
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox","You escaped from "+enemies[num9].name+"!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"supdateGUI3()\">Confirm</button>"
}else {
document.getElementById("body").innerHTML="<div class=\"textbox\" id=\"textbox\"></div>"
printLetterByLetter("textbox",enemies[num9].name+" blocks your path! "+enemies[num9].name+" attacks you!",50)
document.getElementById("body").innerHTML+="<button class=\"option\" onclick=\"battle("+num9+")\">Confirm</button>"
}
}
battle(num9)
}
Every one of the calls in the above code cause the same error. A deeper look reveals that the textbox is there when printLetterByLetter is called and that the destination is textbox. When I console logged document.getElementById(destination) I got null. printLetterByLetter has worked every other time I have used it and I haven't gotten an error when I have used other commands that are similar. My entire code can be found here: https://github.com/Fish767/Space-Clones. The files in question are run.js and letterbyletter.js. Destination is a string and the line before I called printLetterByletter I added the element with an id of textbox.
Steps to reproduce: press move and left twice and then move and explore until you get into a battle. Then press run.
The html doc is this:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/first.css">
<title id="title">Lives in Space</title>
</head>
<body id="body">
<script src="js/globalvars.js"></script>
<script src="js/sleep.js"></script>
<script src="js/letterbyletter.js"></script>
<script src="js/format.js"></script>
<script src="js/cleardoc.js"></script>
<script src="js/doEffects.js"></script>
<script src="js/use.js"></script>
<script src="js/toss.js"></script>
<script src="js/battleresults.js"></script>
<script src="js/friend.js"></script>
<script src="js/run.js"></script>
<script src="js/attack.js"></script>
<script src="js/battle.js"></script>
<script src="js/event.js"></script>
<script src="js/explore.js"></script>
<script src="js/moveto.js"></script>
<script src="js/second.js"></script>
<script src="js/rpgland.js"></script>
<script src="js/loop.js"></script>
</body>
</html>
I can easily do what I want in another way. What I am asking is why doesn't this way work.
I cloned the repo.
There is no "#textbox" in DOM when the error happen, it was replaced with "#statsbox" on battle function. You'll want to use chrome dev tool to debug step by step and it'll help you develop this game more easier also.
Happy coding!
It is because when you click the "confirm" button, you execute battle(0), and the first instruction in this function is to overwrite the entire DOM : document.getElementById("body").innerHTML="<div id=\"statsbox\"></div><div id=\"option-container\"></div>". So everything else disappears.
The reason why you can console.log the element at the beginning of printLetterByLetter() and then 10 lines later it logs null is because those 10 lines are within a setInterval which gets executed later, at the end of the lifecycle. The DOM has been overwritten in-between.

JavaScript does not work on pages other than my MasterPage and pages that aren't linked to it

Sorry for the bad english :P
I'm using ASP.NET
I'm trying to use a JavaScript that I've found on the Internet to set masks to my telephone and cellphone text fields, but the JS code just work at the fields that are located at my MasterPage. I don't have much experience with JS (almost none) and I have no idea how to resolve this since there is no error at my Logcat.
I tried to reference it at my MasterPage's head, body and inside the ContentPlaceHolder.
Here is the JS code:
function mascara(o, f) {
v_obj = o
v_fun = f
setTimeout("execmascara()", 1)
}
function execmascara() {
v_obj.value = v_fun(v_obj.value)
}
function mtel(v) {
v = v.replace(/\D/g, "");
v = v.replace(/^(\d{2})(\d)/g, "($1)$2");
v = v.replace(/(\d)(\d{4})$/, "$1-$2");
return v;
}
function id(el) {
return document.getElementById(el);
}
window.onload = function () {
id('txtTelefone').onkeypress = function () { //Located at MasterPage - working
mascara(this, mtel);
}
id('txtCelular').onkeypress = function () { //Located at MasterPage - working
mascara(this, mtel);
}
id('telefoneContato').onkeypress = function () { //Located at Contact Page - not working
mascara(this, mtel);
}
id('txtCelularUser').onkeypress = function () { //Located at User Page - not working
mascara(this, mtel);
}
id('txtTelefoneUser').onkeypress = function () { //Located at User Page - not working
mascara(this, mtel);
}
}
As I said before I tried to reference my JS file in some places, the codes that I tried were:
<script src="<%# Page.ResolveClientUrl("../Componentes/js/mascaras.js") %>"></script>
<script src="../Componentes/js/mascaras.js"></script>
As you can see, the fields are located in diferent pages, I also tried to put the code directly at the pages but I had no luck.
I think that I don't need to post my entire MasterPage here, then I'll put just the head, but if exists a need I will edit the post.
<head runat="server">
<title></title>
<link rel="shortcut icon" href="../imagens/icone.ico" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<link href="../Componentes/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen" />
<link href="../Componentes/fontawesome/css/font-awesome.min.css" rel="stylesheet" media="screen" />
<link href="../Componentes/css/MasterPage.css" rel="stylesheet" />
<link href="../Fontes/Fontes.css" rel="stylesheet" />
<script src="../Componentes/bootstrap/js/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/debug.addIndicators.min.js"></script>
<script src="../Componentes/bootstrap/js/bootstrap.min.js"></script>
<%--Mask Scripts--%>
<script src="<%# Page.ResolveClientUrl("../Componentes/js/mascaras.js") %>"></script>
<script src="../Componentes/js/mascaras.js"></script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
EDIT 1
Tried this:
id('<%= txtTelefoneContato.ClientID %>').onkeypress = function () { //Located at Contact Page - Still not working
mascara(this, mtel);
}
id('<%= txtCelularUser.ClientID %>').onkeypress = function () { //Located at User Page - Still not working
mascara(this, mtel);
}
id('<%= txtTelefoneUser.ClientID %>').onkeypress = function () { //Located at User Page- Still not working
mascara(this, mtel);
}
The reference to the script is at MasterPage head. But the problem still the same
EDIT2
Im receiving this when I inspect my page:
Error image 1
Error image 2
Resolved
As VDWWD explained, I just put the JS code directly at the .aspx pages with this modification:
from:,
id('txtCelularUser').onkeypress = function () {
mascara(this, mtel);
}
to:
id('<%= txtCelularUser.ClientID %>').onkeypress = function () {
mascara(this, mtel);
}
Thank you in advance
You have to use it like this when accessing elements with JavaScript that have master pages. And it's also better to use it even without master pages. If you should change the ID in you don't have to change it also in your script.
id('<%= txtTelefoneUser.ClientID %>').onkeypress
If you look at the HTML source you will see that the ID of the element has been changed from txtTelefoneUser to something like this ContentPlaceHolder_txtTelefoneUser. Aspnet adds a prefix to ensure every element has a unique ID.
You will see the same usage of prefix in elements that repeat data like GridView/Repeater/DataList etc.
UPDATE
If you put the javascript in an external file you can put a reference to it on the master page like this (assuming Componentes is a folder in the root):
<script src="/Componentes/js/mascaras.js" type="text/javascript"></script>
However putting <%= txtTelefoneUser.ClientID %> in an external file will not work, only on an .aspx page. To make that work declare those elements as variables an assign them on the aspx page while using them in the external js file.
Below a demo:
In the external javascript file:
var myElement;
function myFunction() {
myElement.value = "Success!";
}
and then on the .aspx page:
<script type="text/javascript">
myElement = document.getElementById("<%= TextBox1.ClientID %>");
</script>
After a long time I found that the elements that area inside the Content to be found in javascript must have the name of the content ID in front more undeline and the name of the element ID, you are looking for.
example:
document.querySelector("#ContentPlaceHolder1_img1").setAttribute("src", 123);

Sharepoint Document Library - Filename to title using javascript

Good evening!
I had a working functionality on a sharepoint document library. It's purpose was to copy the name of a file to the title column.
It was working for a long time but after an update to the sharepoint platform it stopped working and i can't figure out why.
The code:
<input type="button" onclick="updateTitleFromName()" value="Update Title from Name" />
<script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript">
function updateTitleFromName(){
var q, res, uRes, count;
count = 0;
q = "<Where><IsNull><FieldRef Name='Title' /></IsNull></Where>";
res = spjs_QueryItems({"listName":_spPageContextInfo.pageListId,"query":q,"viewFields":["ID","FileLeafRef"]});
if(res.count === 0){
alert("No files without title found.");
return;
}
if(!confirm("There are "+res.count+" files to update. The page will appear as frozen while the script is working.\n\nContinue?")){
return;
}
$.each(res.items,function(i,item){
uRes = spjs_updateItem({"listName":_spPageContextInfo.pageListId,"id":item.ID,"data":{"Title":item.FileLeafRef.split(";#")[1]}});
if(!uRes.success){
alert("Could not update the file: "+item.FileLeafRef+" due to the follwing error:\n\n"+uRes.errorText);
}else{
count += 1;
}
});
alert("Updated "+count+" files.");
location.href = location.href;
}
</script>
The error is: TypeError: $spjs is null. And it occurs inside the library spjs-utility library on the spjs_QueryItems call.
Maybe this could be due to a conflictuous library that as added during the updated, but how can i debug this?
Also, if this doesn't work, wouldn't it be simpler to do the same with jQuery? Thats what i'm trying right now, but i'm a beginner as you must have perceived.
Thanks in advance.
Best
I would test if JQuery is loaded or not in your updateTitleFromName function:
if (window.jQuery) {
alert('loaded');
} else {
alert('not loaded');
}
if it is not loaded, try to reference your scripts with absolute urls to see if you can load them:
<script type="text/javascript" src="http://myportal/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://myportal/Scripts/spjs-utility/spjs-utility.js"></script>

Am I calling my JavaScript Function correctly?

I am new to Javascript.
I am making my first Adventure Game.
I tested the following code out with an onClick and it worked fine:
// JavaScript Document
function changeColour()
{
if (document.getElementById('colourTest').style.backgroundColor='yellow')
{
document.getElementById('colourTest').style.backgroundColor='red';
}
else
{
document.getElementByID('colourTest').style.backgroundColor='yellow';
}
}
var direction;
direction = prompt("Which direction would you like to go ?");
if ( direction == "North" )
{
changeColour();
}
else
{
console.log("You can't go in that direction ?");
}
This is the HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script language="javascript" type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body>
<div id="colourTest">
</div>
</body>
</html>
I want the Yellow div to turn red when the user enters the word North, otherwise, the user is told that they can't go in that direction.
I am sure that this is some kind of syntax error :D
Hi, Here is an update:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="Scarry_Adventure_Game.js"></script>
<script type="text/javascript" ></script>
<link rel="stylesheet" href="Scarry_Adventure_Game.css" type="text/css">
</head>
<body onload="load();">
<img id="myimg" alt="My Image" src="images/image1.jpg" />
<form>
<input name="heading" type="text" id="which" value="" />
</form>
</body>
</html>
Here is JS:
// JavaScript Document
var img = new Image();
img.src = "images/image1.jpg";
function whichImage(b)
{
var image = document.getElementById("myimg");
if (b == "North")
{
image.src = "images/image2.jpg";
}
else
{
image.src = "images/image1.jpg";
}
}
function whichDirection (x)
{
if (x == "North" || x == "South" || x == "East" || x == "West" )
{
document.write("You choose to go " + direction);
}
else
{
document.write("You can't go in that direction");
}
}
function load()
{
var direction = document.getElementById('which').value;
whichDirection(direction);
whichImage(direction);
}
I don't understand why the input direction from the user isn't allowing the image to change to image2.jpg, when the word, North is input by the user.
Can JS actually capture text input from html and then use this with variables in functions?
More over, with this version, the DOM doesn't seem to have loaded, as there is no image to be seen.
The two errors I see right away (there may be more) are...
if (document.getElementById('colourTest').style.backgroundColor='yellow')
You're assigning instead of comparing. Use == for comparison (as you do elsewhere). And...
document.getElementByID('colourTest').style.backgroundColor='yellow';
JavaScript is case-sensitive. The function name should be getElementById (as you do elsewhere).
In this case there was a logical error and a syntax error. The latter can often be noticed by looking at the JavaScript console in your browser's debugging tools. If it tried to execute that line of code, you'd see an error there. Logical errors, on the other hand, can be trickier to pinpoint. For those you'll want to familiarize yourself with the debugger in your browser's debugging tools.
You can click on a specific line of JavaScript code to set a "breakpoint" where the execution of code will pause. Once paused, you can examine the runtime values of your variables, step through the execution line-by-line to check its behavior, etc. This is how you validate that the code is doing what you expect it to do.

Categories