Keep returning undefined from function - javascript

I'm having some difficulties with dynamic generation of the function rootFolderId.
What I was looking for, was to dynamically assign the value of variable rootFolder, based on the value of the radio button chosen.But when the .createFolder(rootFolderId,folderName) is called, the return is undefined.
Any help please?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="uploaderForm">
<label for="uploaderForm">Upload multiple Files</label>
<div>
<input type="text" name="applicantName" id="applicantName"
placeholder="Your Name">
</div>
<div class="row">
<p>Zgjidh lenden:</p>
<input type="radio" id="matematike" name="gender" value="1wP_QokwCiUv1cquU-eET7g5AuFITxE9d">
<label for="matematike">Matematike</label><br>
<input type="radio" id="dituri" name="gender" value="1I2aELHikX5f-uD6sCybQd7UevPK4WR3W">
<label for="dituri">Dituri Natyre</label><br>
<input type="radio" id="gjuhe" name="gender" value="18xvXUYQTHGQtmkJIti-S9trqwxTYEZ5P">
<label for="gjuhe">Gjuhe Shqipe</label>
</div>
<div>
<input type="text" name="applicantEmail" id="applicantEmail"
placeholder="Your Email">
</div>
<div>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="output"></div>
<script>
var rootFolderId = function(){
$('#uploaderForm input[type=radio]').on('change', function(event) {
var result = $(this).val();
$('#rootFolderId').html(result);
console.log(result);
})
}();
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function uploadFiles() {
var allFiles = document.getElementById('filesToUpload').files;
var applicantName = document.getElementById('applicantName').value;
if (!applicantName) {
window.alert('Missing applicant name!');
}
var applicantEmail = document.getElementById('applicantEmail').value;
if (!applicantEmail) {
window.alert('Missing applicant email!');
}
var folderName = applicantName + ' ' + applicantEmail;
if (allFiles.length == 0) {
window.alert('No file selected!');
} else {
numUploads.total = allFiles.length;
google.script.run.withSuccessHandler(function(r) {
// send files after the folder is created...
for (var i = 0; i < allFiles.length; i++) {
// Send each file at a time
uploadFile(allFiles[i], r.folderId);
}
}).createFolder(rootFolderId, folderName);
console.log(rootFolderId);
}
}
function uploadFile(file, folderId) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
document.getElementById('output').innerHTML = 'uploading '
+ file.name + '...';
//window.alert('uploading ' + file.name + '...');
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
}
reader.readAsDataURL(file);
}
function onFileUploaded(r) {
numUploads.done++;
document.getElementById('output').innerHTML = 'uploaded '
+ r.fileName + ' (' + numUploads.done + '/'
+ numUploads.total + ' files).';
if (numUploads.done == numUploads.total) {
document.getElementById('output').innerHTML = 'All of the '
+ numUploads.total + ' files are uploaded';
numUploads.done = 0;
}
}
</script>
</body>
</html>
The createFolder() function:
function createFolder(parentFolderId, folderName)
{
try {
var parentFolder = DriveApp.getFolderById(parentFolderId);
var folders = parentFolder.getFoldersByName(folderName);
var folder;
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = parentFolder.createFolder(folderName);
}
return { 'folderId' : folder.getId() }
}
catch (e) {
return { 'error' : e.toString() }
}
}

Related

How to call a javascript function?

I try to call a js function from a razor-file. The script is available in index.html. The number of selected files will be shown. But I expect under the html-text: "Selected files:" the names of the Excel-files. But after selecting nothing is shown.
What do I wrong? And do I solve it?
The blazor-page [importexceldata.razor]
#page "/importexceldata"
#inject IJSRuntime js
<h3>Import Excel Data</h3>
<form>
<div><input id="minimum" type="text" /></div>
<div><input id="maximum" type="text" /></div>
<div></div>
<div></div>
<p><span>Select file(s) to upload :</span></p>
<p>
<input class="btn btn-danger"
id="file" multiple
name="file"
type="file"
onchange="javascript:updateList()" />
</p>
<p>
<input class="btn btn-warning"
id="button1"
type="button"
value="Upload" />
</p>
<p>Selected files:</p>
<div id="fileList"></div>
</form>
#code {
public object UpdateList() => js.InvokeAsync<object>("updateList");
//protected override async Task OnAfterRenderAsync(bool firstRender)
//{
//}
}
... and the index.html
<script type="text/javascript">
window.document.readyState(function(){
$("#button1").click(function (evt) {
var files = $("#file").get(0).files;
var minimum = $("#minimum").val();
var maximum = $("#maximum").val();
if (files.length > 0) {
console.log(files.length);
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
console.log(data);
$.ajax({
type: "POST",
url: "/Home/UploadFiles?minimum=" + minimum + "&maximum=" + maximum,
contentType: false,
processData: false,
data: data,
success: function (messages) {
for (i = 0; i < messages.length; i++) {
alert(messages[i]);
}
},
error: function () {
alert("Error while invoking the Web API");
}
});
}
});
//window.jsMethod = (updateList) => {
updateList = function () {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children += '<li>' + input.files.item(i).name + '</li>';
}
output.innerHTML = '<ul>' + children + '</ul>';
};
</script>
</body>
</html>
Check your function code, There is no return value, So you can't call js like this:
#code {
public object UpdateList() => js.InvokeAsync<object>("updateList");
}
Change your function code like this:
function updateList () {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children += '<li>' + input.files.item(i).name + '</li>';
}
output.innerHTML = '<ul>' + children + '</ul>';
};
Change input code use #onchange=xx:
<input class="btn btn-danger"
id="file" multiple
name="file"
type="file"
#onchange="UpdateList" />
Then call js like this:
#code {
public async Task UpdateList() {
await Js.InvokeVoidAsync("updateList");
}
}
Demo
==================Edit===============
#page "/importexceldata"
#inject IJSRuntime Js
<PageTitle>Index</PageTitle>
<form>
<div><input id="minimum" type="text" /></div>
<div><input id="maximum" type="text" /></div>
<div></div>
<div></div>
<p><span>Select file(s) to upload :</span></p>
<p>
<input class="btn btn-danger"
id="file" multiple
name="file"
type="file"
#onchange="UpdateList" />
</p>
<p>
<input class="btn btn-warning"
id="button1"
type="button"
value="Upload" />
</p>
<p>Selected files:</p>
<div id="fileList"></div>
</form>
#code {
public async Task UpdateList() {
await Js.InvokeVoidAsync("updateList");
}
}
Index
<script type="text/javascript">
$(document).ready(function () {
$("#button1").click(function (evt) {
var files = $("#file").get(0).files;
var minimum = $("#minimum").val();
var maximum = $("#maximum").val();
if (files.length > 0) {
console.log(files.length);
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
console.log(data);
$.ajax({
type: "POST",
url: "/Home/UploadFiles?minimum=" + minimum + "&maximum=" + maximum,
contentType: false,
processData: false,
data: data,
success: function (messages) {
for (i = 0; i < messages.length; i++) {
alert(messages[i]);
}
},
error: function () {
alert("Error while invoking the Web API");
}
});
}
});
});
//window.jsMethod = (updateList) => {
function updateList () {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
var children = "";
for (var i = 0; i < input.files.length; ++i) {
children += '<li>' + input.files.item(i).name + '</li>';
}
output.innerHTML = '<ul>' + children + '</ul>';
};
</script>

How to add conditionals to user input in App Scripts with while loops?

I made a selectBox which had its range of values from a Google Sheet Column. I also want to take an Integer input value from the user and then write this value in a specific cell according to option taken from selectBox. The html link does not show the integer response box. Is it possible to do the above plan in a while loop? Would appreciate any ideas and correction of code
function doGet() {
var ap = SpreadsheetApp.openByUrl("Gsheet URL here");
var ui = SpreadsheetApp.getUi();
var user = ui.prompt("Put down a number");
var result = result.getSelectedButton();
var sheet = ap.getSheetByName("lv");
var values = sheet.getRange("A2:A10").getValues();
var options = values.map(function(row)
{
#To show show the selected option??
var item = options.getSelecteditem();
if (item === A3)
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var a1 = cell.getA3Notation();
var val = cell.getValue();
SpreadsheetApp.getUi().alert("Ur value is "+a1+" value is "+val);
}
{
return '<option value="' + row[0] + '">' + row[0] + '</option>';
});
var html = '<form onSubmit="handleSubmit(this)"> Type of Cuisine' + options.join('') + '</select></form>';
return HtmlService.createHtmlOutput(html);
}
Using an Html Dialog to Control User Inputs
Not sure what you wanted so here's a complete example I whipped up for you.
Code.gs:
function processInput(obj) {
Logger.log(JSON.stringify(obj));
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [min,max,locs] = sh.getRange('B1:B3').getValues().flat();
Logger.log('min: %s max: %s locs: %s',min,max,locs)
const lA = locs.split(',');
if(obj.int > max) {
obj.msg = "Too High Try Again";
return obj;
} else if (obj.int < min) {
obj.msg = "To Low Try Again";
return obj;
} else if (!~lA.indexOf(obj.loc)) {
obj.msg = "Invalid Location";
return obj;
} else {
sh.getRange(obj.loc).setValue(obj.int);
obj.msg = "Complete";
return obj;
}
}
Following function Launches the dialog:
function launchInputDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),"Enter Input");
}
html:
<!DOCTYPE html>
<html>
<head>
</head>
<style>input {margin: 2px 5px 2px 0;}</style>
<body>
<form>
<input type="text" id="in1" placeholder="Enter an integer" />
<br /><input type="text" id="in2" placeholder="Enter a location" />
<br /><input type="button" value="Process" onClick="processinput();" />
</form>
<div id="msg"></div>
<script>
function processinput() {
document.getElementById("msg").innerHTML = '';
let v1 = parseInt(document.getElementById('in1').value);
let v2 = document.getElementById('in2').value;
let obj = {int:v1,loc:v2,msg:''};
google.script.run
.withSuccessHandler(robj => {
console.log(JSON.stringify(robj))
if(robj.msg == "Complete") {
document.getElementById("msg").innerHTML = `Value: ${robj.int} Location: ${robj.loc} Try Again`;
document.getElementById("in1").value = '';
document.getElementById("in2").value = '';
} else {
document.getElementById("msg").innerHTML = robj.msg;
}
})
.processInput(obj);
}
</script>
</body>
</html>
Short Demo:
This version uses a <select> tag to allow the user to determine where the data will be loaded
GS:
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.getRange(data.loc).setValue(data.id)
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params = { "contentType": "application/json", "payload": JSON.stringify(obj), "muteHttpExceptions": true, "method": "post", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
UrlFetchApp.fetch(url, params);
}
function displayError(msg) {
SpreadsheetApp.getUi().alert(msg);
}
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'My Dialog');
}
function getSelectOptions() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Options');
var rg = sh.getDataRange();
var vA = rg.getValues();
var options = [];
for (var i = 0; i < vA.length; i++) {
options.push(vA[i][0]);
}
return vA;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/>
<select id="sel1" name="loc"></select>
<input type="button" value="submit" onClick="processForm(this.parentNode);" />
</form>
<script>
function processForm(obj) {
console.log(obj.id.value);
if(obj.id.value.match(/[A-Za-z]/)) {
google.script.run.displayError("Invalid Characters Found in id field");
} else {
google.script.run.sendData(obj);
}
}
window.onload = function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
}
function updateSelect(vA) {
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
</body>
</html>
Demo:

Uncaught SyntaxError: Unexpected end of input -- HTML Element Deletion in JavaScript/JQuery

I'm trying to create this form where I can have a button which will add a duplicate, and a button that will delete the current 'new form'. All functionality is working aside from the removal of the form-- I'm trying to use JQuery's .remove function but this error began presenting itself as soon as I added it.
I'm almost 100% certain that all parentheses/brackets are aligned-- I ran it through several linting sites to make sure.
Any ideas from looking at the javascript portion of the code?
<!DOCTYPE html>
<html>
<head>
<title>Add a New Course</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.buttonHolder {
text-align: center;
}
</style>
</head>
<body onload="loadXMLDoc_makeCatArray()">
<form action="" id="courseForm">
<div class = "div1">
<fieldset>
<legend>Enter course info:</legend>
Course title: <br>
<input type="text" id="displayName1" value=""><br>
Category: <br>
<select name="categoryDropdown" id="category1"></select><br>
Duration: <br>
<input type="time" id="duration1" value=""><br>
Subcategory: <br>
<input type="text" id="subcategory1" value=""><br>
Description: <br>
<textarea rows="4" cols="60" id="description1"></textarea><br>
URL: <br>
<input type="text" id="url1" value=""><br>
ID: <br>
<input type="text" id="id1" value=""><br>
Table ID: <br>
<input type="text" id="tableId1" value=""><br>
<div class="buttonHolder">
<input type="button" value="Submit All" onclick="javascript: loadXMLDoc();">
<input type="button" value="New Course" onclick="javascript: addCourseForm();">
</div>
</fieldset>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/vkbeautify.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/MicrosoftAjaxCore.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="https://unpkg.com/sharepointplus#5.1.0/sharepointplus-5.1.js"></script>
<script>
//Initialize the number of forms being submitted as 1
var count = 1;
function addCourseForm()
{
//Get the course form element
var course = document.getElementById("courseForm");
//Error checking here, making sure we got courseForm
if (course)
{
//Create a new <div> element which contains the form
var newDiv = document.createElement("div");
newDiv.className = "div" + (count + 1);
var divName = "div" + (count + 1);
newDiv.innerHTML = '<fieldset> <legend>Enter course info:</legend> Course title: <br> <input type="text" id="courseTitle' + (count + 1) + '"><br> Category: <br> <select name="categoryDropdown" id="category' + (count + 1) + '" value=""></select><br> Duration: <br> <input type="time" id="duration' + (count + 1) + '" value=""><br> Subcategory: <br> <input type="text" id="subcategory' + (count + 1) + '" value=""><br> Description: <br> <textarea rows="4" cols="60" id="description' + (count + 1) + '"></textarea><br> URL: <br><input type="text" id="url' + (count + 1) + '" value=""><br> <div class="buttonHolder"> <input type="button" value="Submit All" onclick="javascript: loadXMLDoc();"> <input type="button" value="New Course" onclick="javascript: addCourseForm();"> <input type="button" value="Remove Course" onclick="removeCourseForm(' + divName + ');"> </div> </fieldset>';
//Appends the new <p> element to the other forms
course.appendChild(newDiv);
//Add one to the number of forms being submitted
count++;
loadXMLDoc_makeCatArray();
}
}
function removeCourseForm(paragraph) {
$("." + paragraph).remove();
count--;
}
function loadXMLDoc_submitFormData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
submitFormData(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/curriculumdata.xml", true);
xmlhttp.send();
}
function submitFormData(xml)
{
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
for (var x = 1; x <= count; x ++) {
var p = xmlDoc.getElementsByTagName("course")[1];
var p_prime = p.cloneNode(false);
xmlDoc.getElementsByTagName("curriculumdata")[0].appendChild(p_prime);
var br = xmlDoc.createElement("br");
var elements = ["category", "description", "displayName", "duration", "id", "subcategory", "tableId", "url"];
for (var y = 0; y < elements.length; y++){
console.log(elements[y] + x);
newElement = xmlDoc.createElement(elements[y]);
if (y == 0) {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).text);
} else {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).value);
}
newElement.appendChild(newText);
console.log(newElement);
xmlDoc.getElementsByTagName("course")[xmlDoc.getElementsByTagName("course").length - 1].appendChild(newElement);
}
};
var clientContext = new SP.ClientContext('https://splm.sharepoint.com/sites/OCB');
var oList = clientContext.get_web().get_lists().getByTitle('Course List');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
var documents = new XMLSerializer().serializeToString(xmlDoc.documentElement);
documents = vkbeautify.xml(documents);
oListItem.set_item('xml_data', documents);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
};
function onQuerySucceeded() {
alert('Course successfully added');
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function loadXMLDoc_makeCatArray() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
catArray(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/curriculumdata.xml", true);
xmlhttp.send();
}
function catArray(xml){
eleArray = [];
var xmlDoc = xml.responseXML;
ele = xmlDoc.getElementsByTagName("course");
for (i = 0; i < ele.length; i++) {
if(!(eleArray.includes(ele[i].getElementsByTagName("category")[0].childNodes[0].nodeValue))){
eleArray.push(ele[i].getElementsByTagName("category")[0].childNodes[0].nodeValue);
}
}
var sel = document.getElementsByName('categoryDropdown')[count - 1];
for(var i = 0; i < eleArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = eleArray[i];
opt.value = eleArray[i];
console.log(opt);
sel.appendChild(opt);
}
};
</script>
</body>
</html>
First, your HTML is not valid because you cannot have anything after </body> except </html>. All that scripting should be moved to just before the closing body tag. Additionally, it's invalid to nest a fieldset in a p. You could make that p a div.
Next, count --; needs to be count--;
The unexpected input is the space after the count variable reference.
And your manually built HTML string needs to be looked at because you have nested double quotes in double quotes and you are concatenating nothing after count:
onclick="javascript: removeCourseForm("p' + count + '");">
This would also result in the same error because you have a trailing + but then nothing to concatenate it to.
Having said that....You really shouldn't be taking this approach in the first place.
Instead of creating an huge string of concatenated HTML (which is where your issue lies), just clone the first fieldset. Now, because we're going to clone, we want to get away from using id attributes and instead use .querySelector() and .querySelectorAll() to find elements based on CSS selectors.
You also should stop using .getElementsByTagName() because it has performance impact and you aren't interested in the collection that it returns anyway, you are passing an index to the collection. Instead use .querySelector().
Lastly, don't use inline event handlers (onclick). Do you event binding in JavaScript.
See the comments below.
Here's a working example.
<!DOCTYPE html>
<html>
<head>
<title>Add a New Course</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.buttonHolder {
text-align: center;
}
</style>
</head>
<body>
<form action="" id="courseForm">
<fieldset>
<legend>Enter course info:</legend>
Course title:
<br>
<input type="text" class="displayName">
<br> Category:
<br>
<select name="categoryDropdown" class="category"></select>
<br> Duration:
<br>
<input type="time" class="duration">
<br> Subcategory:
<br>
<input type="text" class="subcategory">
<br> Description:
<br>
<textarea rows="4" cols="60" class="description"></textarea>
<br> URL:
<br>
<input type="text" id="url1">
<br> ID:
<br>
<input type="text" id="id1">
<br> Table ID:
<br>
<input type="text" id="tableId1">
<br>
<div class="buttonHolder">
<input type="button" value="Submit All" class="submitAll">
<input type="button" value="New Course" class="newCourse">
</div>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/vkbeautify.js"></script>
<script src="https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/js/MicrosoftAjaxCore.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.0/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="https://unpkg.com/sharepointplus#5.1.0/sharepointplus-5.1.js"></script>
<script>
//Get the course form element
var course = document.getElementById("courseForm");
document.querySelector(".submitAll").addEventListener("click", loadXMLDoc_submitFormData);
document.querySelector(".newCourse").addEventListener("click", addCourseForm);
function addCourseForm() {
var firstFS = document.querySelector("fieldset");
//Error checking here, making sure we got courseForm
if (course) {
// >>> **** Clone the current fieldset ***** <<<<
var newFS = firstFS.cloneNode(true);
// Create and configure remove button
var removeBtn = document.createElement("button");
removeBtn.textContent = "Remove Course";
removeBtn.type = "button";
removeBtn.addEventListener("click", function() {
// Call the remove function but pass the fieldset
// that this button is part of
removeCourseForm(this.closest("fieldset"));
});
// Append the new button to the new fieldset
newFS.querySelector("div.buttonHolder").appendChild(removeBtn);
//Appends the new <p> element to the other forms
course.appendChild(newFS);
// ***********************************************
loadXMLDoc_makeCatArray();
}
}
function removeCourseForm(fs) {
fs.remove();
}
function loadXMLDoc_submitFormData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
submitFormData(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/Testing/curriculumdata.xml", true);
xmlhttp.send();
}
function submitFormData(xml) {
var xmlDoc = xml.responseXML;
console.log(xmlDoc);
for (var x = 1; x <= count; x++) {
var p = xmlDoc.getElementsByTagName("course")[1];
var p_prime = p.cloneNode(false);
xmlDoc.querySelector("curriculumdata").appendChild(p_prime);
var br = xmlDoc.createElement("br");
var elements = ["category", "description", "displayName", "duration", "id", "subcategory", "tableId", "url"];
for (var y = 0; y < elements.length; y++) {
console.log(elements[y] + x);
newElement = xmlDoc.createElement(elements[y]);
if (y == 0) {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).text);
} else {
newText = xmlDoc.createTextNode(document.getElementById(elements[y] + x).value);
}
newElement.appendChild(newText);
console.log(newElement);
xmlDoc.querySelectorAll("course")[xmlDoc.getElementsByTagName("course").length - 1].appendChild(newElement);
}
};
var clientContext = new SP.ClientContext('https://splm.sharepoint.com/sites/OCB');
var oList = clientContext.get_web().get_lists().getByTitle('Course List');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
var documents = new XMLSerializer().serializeToString(xmlDoc.documentElement);
documents = vkbeautify.xml(documents);
oListItem.set_item('xml_data', documents);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
};
function onQuerySucceeded() {
alert('Course successfully added');
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function loadXMLDoc_makeCatArray() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
catArray(this);
}
};
xmlhttp.open("GET", "https://splm.sharepoint.com/sites/OCB/Shared%20Documents/curriculumdata.xml", true);
xmlhttp.send();
}
function catArray(xml) {
eleArray = [];
var xmlDoc = xml.responseXML;
ele = xmlDoc.getElementsByTagName("course");
for (i = 0; i < ele.length; i++) {
if (!(eleArray.includes(ele[i].querySelector("category").childNodes[0].nodeValue))) {
eleArray.push(ele[i].querySelector("category").childNodes[0].nodeValue);
}
}
var sel = document.querySelector('categoryDropdown')[count - 1];
for (var i = 0; i < eleArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = eleArray[i];
opt.value = eleArray[i];
console.log(opt);
sel.appendChild(opt);
}
};
loadXMLDoc_makeCatArray();
</script>
</body>
</html>
So I ended up fixing this problem rather simply:
I called the function removeCourseForm() without any parameters, and then generated the div name inside of that function.
function removeCourseForm() {
var divName = "div" + count;
$("." + divName).remove();
count--;
}
This seems to have remedied the whole issue and it works nicely now :)

Can't find the variable "SSL" javascript

ERROR: Can't find variable SSL
Good morning, I was finishing the script when I find a problem that I couldn't solve. When I click on a button, it tells me can't find the variable "SSL" but it is created (just show the error when I click one button), can you tell me if there are some misstake?
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = ss =function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.name.push(url.trim());
el.value = '';
this.FetchAll();
}
if (url) {
MyJSON.url.push(url1.trim());
el1.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.urls.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.name.splice(item, 1);
this.FetchAll();
};
}
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
}
Solved, the variable SSL was into start so, it wasn't global variable.
I needed to do window.SSL = SSL and It works.
Thanks you CertainPerformance and #Chriag Ravindra

how to validate URL in dynamically added textbox

how to check URL is correct or not when i will enter into dynamically added textbox .
here t3 is given as id of input tag but that is works only for first dynamically added textbox not for others.
how to validate another URL present into next dynamically added textbox ?
<script type="text/javascript">
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" id = "t3" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
</script>
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex .test(document.getElementById('t2').value)||!regex .test(document.getElementById('t3').value))
{
alert("Please enter valid URL.");
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
HTML - index.html
<html>
<head>
<title>T-SUMM</title>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
function check()
{
if (document.getElementById('t1').value==""
|| document.getElementById('t1').value==undefined)
{
alert ("Please Enter a Query");
return false;
}
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
var boxes = document.getElementsByTagName('input');
for(i = 0; i < boxes.length; i++) {
if(boxes[i].type == "text" && boxes[i].className==="urls" && !regex.test(boxes[i].value)) {
alert("Please enter valid URL. Error in Text Box "+boxes[i].value);
return false;
}
}
return true;
}
</script>
</head>
<body>
<center>
<form method="Post" action="./result.jsp">
<table>
<br><br><Label> Enter a Query : </label>
<input name='habits' id='t1'> <br><br>
<Label> Enter the URL : </label>
<input name='habits' class="urls" id='t2'>
<input id="btnAdd" type="button" value="add another URL" onclick="AddTextBox()" /><br><br>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<input type="submit" name="submit" onclick="return check();">
</table>
</form>
</body>
</html>
JS - script.js
function GetDynamicTextBox(value){
return '<Label> Enter the URL : </label>' +
'<input name = "habits" type="text" class="urls" value = "' + value + '" />' +
' <input type="button" value="Remove" onclick = "RemoveTextBox(this)" /><br><br>'
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
window.onload = RecreateDynamicTextboxes;
I think you can first try to add an "onchange" handler to the "TextBoxContainer" div and user event.target or event.srcElement to identify whether it is a textbox that triggered the "onchange" event. If the trigger dom is exactly the ones you want, then you can try to validate its value and if it is not, you don't need to do anything. If this is done, then the rest things will be simply add/remove textboxes to the container element. Below are some sample codes that may help:
<script type="text/javascript">
var _container = document.getElementById('TextBoxContainer');
function add(){
var _txt = document.createElement("INPUT");
_txt.type = "text";
_container.appendChild(_txt);
}
_container.onchange = function(event){
var _dom = event.target || event.srcElement;
if(_dom && _dom.tagName === "INPUT" && _dom.type === "text"){
//alert(_dom.value);
//You can validate the dom value here
}
};
document.getElementById('add').onclick=function(){
add();
};
</script>

Categories

Resources