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>
Related
I am having issues trying to run an API using Geocodio. This is set up through WordPress and I would really appreciate any help I can get!
Everything works up until the actual API itself has to run. The Geocodio documentation states that it runs "using a jQuery AJAX call". I have tried multiple script sources that claim to fix the problem, but I get the error that "superfish() is not a function" or that "Cannot read properties of undefined (reading 'get')".
<head>
<script src="jQuery.js"></script>
<script src="superfish.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('ul.sf-menu').superfish();
});
</script>
</head>
<body>
<input type="text" id="myTxt" style="width: 400px;" placeholder="Type Your Address Here!"></input>
<input type="submit" id="myBtn" value="Search Now!"></input>
<script>
var submit = document.getElementById("myBtn")
var myInput = document.getElementById("myTxt")
submit.addEventListener("click", geocodio)
function geocodio() {
if(myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
$.get('https://api.geocod.io/v1.7/geocode?q='+ encodeURIComponent(myInput)
+'&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results)});
}
};
</script>
</body>
You must be using some strange version of jQuery that forces you to refer to it as jQuery and not $. Odd, I thought all versions of jQuery also set up the $ global.
Try replacing $ with jQuery inside geocodio():
function geocodio() {
if (myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
jQuery.get('https://api.geocod.io/v1.7/geocode?q=' + encodeURIComponent(myInput.value)
+ '&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results);
});
}
}
(also fixed: encode myInput.value instead of encoding whole input)
If that doesn't work, perhaps jQuery.js failed to load. Check the console messages and/or network trace tab in the developer tools.
If that doesn't work, try stepping thru the code using the JavaScript debugger built in to your browser (short tutorial video).
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
I'm currently using this bit of code in a content editor on the newform in a sharepoint list to check and make sure there is an attachment on a new item form:
<script type="text/javascript" language="javascript">
function PreSaveAction() { if
(document.getElementById('idAttachmentsRow').style.display=='none' ) { >
alert('Attachment is Mandatory! Please attach Documents.'); return false ; }
else { return true; } } </script>
Is there anyway to use some similar code to make sure a user only uploads 1 attachment and not multiples?
Bonus question: Is there a simple method to either set a column value when a user changes/upload a different/new attachment or replaces the current one atatched to a sharepoint list item?
Try below js solution.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
function PreSaveAction() {
var attachementCount=$('#idAttachmentsTable').find('tr').length;
if (attachementCount < 1) {
alert("Attachment is Mandatory!");
return false;
} else
return true;
}
</script>
I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}
I have a setup to display something when it detects adblock, and it's displaying code instead of working. I am not that experienced in Javascript to know why.
Okay, in my index file I have
<script type="text/javascript" src="inls/advertisement.js"></script>
Now in advertisement.js I have
document.write('<div id="tester">an advertisement</div>');
And now I have the following in my index after that:
<script type="text/javascript">
if (document.getElementById("tester") != undefined)
{
document.write('<center><script type="text/javascript"><!--google_ad_client = "ca-pub-3846434391631935";/* talknow */google_ad_slot = "6591659297";google_ad_width = 728; google_ad_height = 90; //--> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></center>');
} else {
document.write('<p class="no">We\'ve detected that you\'re using <strong>AdBlock Plus</strong> or some other adblocking software. Please be aware that this is only contributing to the demise of the site. We need money to operate the site, and almost all of that comes from our online advertising. Its not nice to steal.<!-- end .content --></p>');
}
</script>
but where that code is, it displays as this:
Can anyone help?
I took a look at your actual website's source code. It's different to what you posted:
<script type="text/rocketscript">
if (document.getElementById("tester") != undefined)
{
document.write('<center><script type="text/javascript"><!--google_ad_client = "ca-pub-3846434391631935";/* talknow */google_ad_slot = "6591659297";google_ad_width = 728; google_ad_height = 90; //--> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></center>'); } else {
document.write('<p class="no">We\'ve detected that you\'re using <strong>AdBlock Plus</strong> or some other adblocking software. Please be aware that this is only contributing to the demise of the site. We need money to operate the site, and almost all of that comes from our online advertising. Its not nice to steal.<!-- end .content --></p>'); }
</script>
Based on Why is wordpress placing "text/rocketscript" instead of "text/javascript" when using wp_register_script()? it seems like you need to change your <script> tag to:
<script data-cfasync="false" type="text/javascript>
Also, document.write is considered "bad practice"; you should probably use DOM manipulation instead, i.e. something like:
var adblock = document.createElement('p');
adblock.className = 'no';
adblock.innerHTML = 'Some text here';
var content = document.getElementById('content');
content.insertBefore(adblock, content.firstChild);