How to have getElementbyId different than Null after page loaded - javascript

I am using Mustache to generate pages based on Data.
My problem: I need to getElementbyid in the page generated by Mustache. However, it always returns NULL. Do you have any ideas how I can fix it ? (I left a comment in main.js in the part where I am having issues.)
3 pages to reproduce my case:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="test-id">
<!-- Generated Content -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
<script src="../node_modules/file-system/file-system.js"></script>
</body>
</html>
template_page.html (where Mustache generate a page based on Data)
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="template-div">
<!-- part filled by Mustache -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
<script src="../node_modules/file-system/file-system.js"></script>
</body>
</html>
And the javascript part
main.js
document.addEventListener('DOMContentLoaded', function() {
// I get NULL but I want to find a way to get a None null value !!!
console.log(document.getElementById("test-get-id-value"));
// Data to get the different pages
var ALL_DATA = [
{
'lastname': 'lastname_1',
'firstname': 'firstname_1'
},
{
'lastname': 'lastname_2',
'firstname': 'firstname_2'
},
{
'lastname': '"lastname_3"',
'firstname': 'firstname_3'
}
];
// Function to get the different links
function displayData(obj_name) {
var theDiv = document.getElementById("test-id");
obj_name.forEach(doc => {
var lastname = doc['lastname'];
var firstname = doc['firstname'];
newdiv = document.createElement("div")
var text = document.createTextNode(lastname + ' ' + firstname);
var anchor_value = document.createElement("a")
url = lastname + firstname + '.html'
anchor_value.setAttribute("href", "template_page.html" + "?firstname=" + firstname + "&lastname=" + lastname);
anchor_value.setAttribute("class", "link-a");
anchor_value.onclick = createPage();
anchor_value.appendChild(document.createTextNode("Contact him"));
newdiv.appendChild(text);
newdiv.appendChild(anchor_value);
theDiv.appendChild(newdiv);
});
};
displayData(ALL_DATA);
// Function to create the PAGE based on the Data
function createPage() {
// get url parameters
var url = new URL(window.location.href);
var firstname_value = url.searchParams.get("firstname");
var lastname_value = url.searchParams.get("lastname");
// get the data needed
data = {
'lastname': lastname_value,
'firstname': firstname_value
};
var template =
`
<h1> Welcome, {{firstname}} </h1>
<h2> Your last name: {{lastname}} </h2>
<form id="test-get-id-value">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
`
var html = Mustache.render(template, data);
$("#template-div").html(html);
};
});

Your listener for DOMContentLoaded fires when you first load your page, and at that instant, no html has been rendered by Mustache
You can get the non-null value only after the template is rendered, so execute all your logic after render of the template:
var html = Mustache.render(template, data);
$("#template-div").html(html);
var el = document.getElementById("test-get-id-value");
// Now run the logic you need

Related

Function not working when placed in js file

Hi this is working when I include the code inside of my html but when I shift it out into myScript.js I get no results, can anyone point out where I've gone wrong with this as I'd like to be able to access this function across several pages?
I've also got the side issue that if I enter something, then delete the input value my filtered array shows all the options, is it possible to set this to a "" value if the input box contains no value?
Thanks
function page_search(){
var pages = [
{name: "Test",url: "Test.html"},
{name: "Rest",url: "Rest.html"},
{name: "Best",url: "Best.html"},
];
let input = document.getElementById('searchbar').value
input=input.toLowerCase();
let x = document.getElementById('searchresults');
var results = [];
for(var i=0;i<pages.length;i++){
if(pages[i].name.toLowerCase().indexOf(input) > -1)
results.push("<a href='"+pages[i].url+"' target='_blank'>"+pages[i].name+"</a>")
}
if(results.length == 0)
$(x).html("No Results Found");
else
$(x).html(results.join("<br>"));
return results;
}
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="myScript.js"></script>
</head>
<body>
<div class="searchbar">
<input type="text" id="searchbar" onkeyup="page_search()" placeholder="" value="Search.." maxlenght="25" autocomplete="off"/>
</div>
<div id="searchresults"></div>
</body>
</html>
I have added the code, it will definitely resolve your second issue of displaying "" when input box is empty. I am not able to replicate your first issue, can you please tell what is error you are getting ?
function page_search() {
var pages = [{
name: "Test",
url: "Test.html"
},
{
name: "Rest",
url: "Rest.html"
},
{
name: "Best",
url: "Best.html"
},
];
let input = $('#searchbar').val().toLowerCase()
let x = $('#searchresults');
var results = [];
if (input) {
for (var i = 0; i < pages.length; i++) {
if (pages[i].name.toLowerCase().indexOf(input) > -1) {
results.push(`${pages[i].name}`);
}
}
} else {
$(x).html("");
return;
}
if (results.length == 0)
$(x).html("No Results Found");
else
$(x).html(results.join("<br>"));
}
var ele = document.getElementById('searchbar');
ele.addEventListener('keyup', page_search);
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="searchbarC">
<input type="text" id="searchbar" placeholder="Search.." maxlenght="25" />
</div>
<div id="searchresults"></div>
<script src="myScript.js" type="text/javascript"></script>
</body>
</html>

Save value in reload page javascript

I want to save data in the input when the page reloading and I don't
know why my code doesn't work. This is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<label>nom:</label> <input type="text" value=""/></br>
<label>prenom:</label><input type="text" value=""/>
<script type="text/javascript">
window.onbeforeunload = function(){
localStorage.setItem(nom, document.getElementsByTagName('input')[0].value);
localStorage.setItem(prenom, document.getElementsByTagName('input')[1].value);
}
document.addEventListener("DOMContentLoaded",function(){
var nom = localStorage.getItem(nom);
var prnom = localStorage.getItem(prenom);
if(nom!==null&&prenom!==null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
});
</script>
</body>
</html>
Make sure to use quotes for the variable name:
localStorage.setItem('nom', document.getElementsByTagName('input')[0].value);
Or you can use this which is simpler:
localStorage.nom = document.getElementsByTagName('input')[0].value;
Your code was setting the localStorage values when the page was loaded which means it set it to be no text so the code won't save.
Use the below code:
window.onbeforeunload = function() {
var nom = localStorage.nom;
var prnom = localStorage.prenom;
if (nom !== null && prenom !== null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
};
<label>nom:</label> <input type="text" onchange="localStorage.nom = document.getElementsByTagName('input')[0].value" /></br>
<label>prenom:</label><input type="text" onchange=" localStorage.prenom = document.getElementsByTagName('input')[1].value" />
IMPORTANT: use the code on your computer because localStorage doesn't work on stack overflow snippets

save contact to android application using cordova

I have this code:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
function saveContact(wtspNum) {
var myContact = navigator.contacts.create({"displayName": "AnyScan"});
var name = new ContactName();
name.givenName = "example";
name.familyName = " ";
contact.name = name;
var phoneNumbers = [];
phoneNumbers[0] = new ContactField('mobile', wtspNum);
contact.phoneNumbers = phoneNumbers;
contact.save();
};
</script>
</head>
<body>
</script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/app/conInfo.php",function(result){
$.each(result, function(i, field){
$("#contact").append("<a href='javascript:saveContact("+field.wtspNum+");'><img src='/im/wtsp.jpg'></a>");
});
});
});
</script>
<div id="contactInfo" >
<div id="contact" ></div>
</div>
</body>
</html>
I want that when someone press the picture, it will call the saveContact function and save a number to the contact list of an android phone. Any help please..
I have made a php file in the server side that create a vcf card file then dowloaded to the cell phone.. I haven't find another way to do that

Uncaught ReferenceError: Type is not defined in sp.runtime.js

I am trying to use the taxonomy Picker example from Office PnP.
I just want to bind one field to one managed metadata term.
The errors I got are here:
http://screencast.com/t/nOaTusUH4V
The code I have is:
<head>
<meta charset="utf-8" />
<title>Learning bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<link href="../Content/bootstrap-theme.min.css" rel="stylesheet" />
<link rel="Stylesheet" type="text/css" href="../Content/taxonomypickercontrol.css" />
<script src="../Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script src="../Scripts/app.js" type="text/javascript"></script>
<script src="../Scripts/taxonomypickercontrol.js" type="text/javascript"></script>
</head>
body>
<div id="divSPChrome"></div>
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>Create project site</h2>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Project name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Project name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Domain</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword3" placeholder="Domain">
<div class="ms-core-form-line" style="margin-bottom: 0px;">
<input type="hidden" id="taxPickerContinent" />
</div>
</div>
</div>
As you can see I have the hidden field.
And my App.js file is:
// variable used for cross site CSOM calls
var context;
// variable to hold index of intialized taxPicker controls
var taxPickerIndex = {};
//Wait for the page to load
$(document).ready(function () {
//Get the URI decoded SharePoint site url from the SPHostUrl parameter.
var spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var spLanguage = decodeURIComponent(getQueryStringParameter('SPLanguage'));
//Build absolute path to the layouts root with the spHostUrl
var layoutsRoot = spHostUrl + '/_layouts/15/';
//load all appropriate scripts for the page to function
$.getScript(layoutsRoot + 'SP.Runtime.js',
function () {
$.getScript(layoutsRoot + 'SP.js',
function () {
//Load the SP.UI.Controls.js file to render the App Chrome
$.getScript(layoutsRoot + 'SP.UI.Controls.js', renderSPChrome);
//load scripts for cross site calls (needed to use the people picker control in an IFrame)
$.getScript(layoutsRoot + 'SP.RequestExecutor.js', function () {
context = new SP.ClientContext(appWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
context.set_webRequestExecutorFactory(factory);
});
//load scripts for calling taxonomy APIs
$.getScript(layoutsRoot + 'init.js',
function () {
$.getScript(layoutsRoot + 'sp.taxonomy.js',
function () {
//bind the taxonomy picker to the default keywords termset
//$('#taxPickerKeywords').taxpicker({ isMulti: true, allowFillIn: true, useKeywords: true }, context);
$('#taxPickerContinent').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "51f18389-f28a-4961-a903-ee535f7c620d", levelToShowTerms: 1 }, context, initializeCountryTaxPicker);
taxPickerIndex["#taxPickerContinent"] = 0;
});
});
});
});
});
function initializeCountryTaxPicker() {
//if (this._selectedTerms.length > 0) {
// $('#taxPickerCountry').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "0cc96f04-d32c-41e7-995f-0401c1f4fda8", filterTermId: this._selectedTerms[0].Id, levelToShowTerms: 2, useTermSetasRootNode: false }, context, initializeRegionTaxPicker);
// taxPickerIndex["#taxPickerCountry"] = 4;
//}
}
function initializeRegionTaxPicker() {
//if (this._selectedTerms.length > 0) {
// $('#taxPickerRegion').taxpicker({ isMulti: false, allowFillIn: false, useKeywords: false, termSetId: "0cc96f04-d32c-41e7-995f-0401c1f4fda8", filterTermId: this._selectedTerms[0].Id, levelToShowTerms: 3, useTermSetasRootNode: false }, context);
// taxPickerIndex["#taxPickerRegion"] = 5;
//}
}
function getValue(propertyName) {
if (taxPickerIndex != null) {
return taxPickerIndex[propertyName];
}
};
//function to get a parameter value by a specific key
function getQueryStringParameter(urlParameterKey) {
var params = document.URL.split('?')[1].split('&');
var strParams = '';
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split('=');
if (singleParam[0] == urlParameterKey)
return singleParam[1];
}
}
function chromeLoaded() {
$('body').show();
}
//function callback to render chrome after SP.UI.Controls.js loads
function renderSPChrome() {
var icon = decodeURIComponent(getQueryStringParameter('SPHostLogoUrl'));
//Set the chrome options for launching Help, Account, and Contact pages
var options = {
'appTitle': document.title,
'appIconUrl': icon,
'onCssLoaded': 'chromeLoaded()'
};
//Load the Chrome Control in the divSPChrome element of the page
var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
chromeNavigation.setVisible(true);
}
Type is defined in the MicrosoftAjax.js file. You can get access to it by using the following script tag to get it from the aspnet CDN:
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
You do not need the ScriptManager.
It's likely due to the order in which you register the scripts. Referenced libraries should be registered before the scripts that use them. It is easiest to check your page in the browser, you'll see the order in which they load.
You load SP.Runtime.js and SP.js twice. Once on the head and on document ready. Try to remove one of them, but the error can be another I see more error before 404.
you're missing the scriptmanager. Put it above <div id="divSPChrome"></div>
<asp:ScriptManager ID="ScriptManager" runat="server" EnableCdn="True" />
When your are working in html pages, just try to reference this after loading jquery.
<script src="https://ajax.aspnetcdn.com/ajax/4.0/MicrosoftAjax.js" type="text/javascript"></script>

Javascript/JSON error: not well formed

I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')

Categories