Create element "datalist"? - javascript

How to create datalist dynamically?
Was able to dynamically create a drop down using create element and append child but am struggling with datalist.
<script>
let counter = 0;
function myFunction3() {
if (counter < 5) {
counter++;
/*var text = document.createElement("TEXTAREA");
text.id = "text" + counter;
document.body.appendChild(text);*/
var drdwn = document.createElement("datalist");
drdwn.id = "drdwn" + counter;
document.body.appendChild(drdwn);
var opt1 = document.createElement("option");
opt1.text = "<";
opt1.value = "<";
document.getElementById("drdwn" + counter).appendChild(opt1);
var opt2 = document.createElement("option");
opt2.text = ">";
opt2.value = ">";
document.getElementById("drdwn" + counter).appendChild(opt2);
var opt3 = document.createElement("option");
opt3.text = "=";
opt3.value = "=";
document.getElementById("drdwn" + counter).appendChild(opt3);
/*var value = document.createElement("TEXTAREA");
value.id = "value" + counter;
document.body.appendChild(value);*/
}
}
</script>

const options = document.querySelector('.options');
const datalistCreator = document.querySelector('.datalist-creator');
const datalistsBlock = document.querySelector('.datalists');
let counter = 0;
datalistCreator.addEventListener('click', function() {
const datalist = document.createElement('datalist');
const output = document.createElement('input');
datalist.setAttribute('id', 'datalist' + counter);
output.setAttribute('list', 'datalist' + counter);
output.placeholder = 'Datalist of ' + options.value;
for (let i = 0; i < options.value; i++) {
const option = document.createElement('option');
option.value = i + 1;
datalist.appendChild(option)
}
datalistsBlock.appendChild(datalist);
datalistsBlock.appendChild(output);
counter++;
return output;
})
<input type="text" class="options">
<button class="datalist-creator">Create datalist</button>
<div class="datalists"></div>

Related

Javascript dynamic adding mutiple drop down list

i want to achieve a dynamic form that will be generated when the button is pressed through javascript. right now only the textbox is working.
this is the drop down list in html and which i want to achieve in js dynamically using button
<form>
<select id="height">
<option value="Math.min(Math.max((2/-900*supposearea + 11.7222222222222),9.5),11.5)">method 1</option>
<option value="Math.min(Math.max((2/-900*supposearea + 10.2222222222222),8),10)">method 2</option>
</select>
</form>
the below is the js
var height = eval(document.getElementById("height").value);
right now i want to put the drop down into the add button code below
function add_field(){
var total_text=document.getElementsByClassName('input_text');
total_text=total_text.length+1;
var p = document.createElement('p');
p.setAttribute('id', 'input_text'+total_text+'_wrapper');
var input1 = document.createElement('input');
input1.setAttribute('type', 'text');
input1.setAttribute('class', 'input_text');
input1.setAttribute('id', 'length'+total_text);
p.appendChild(input1);
var input2 = document.createElement('input');
input2.setAttribute('type', 'text');
input2.setAttribute('class', 'input_text');
input2.setAttribute('id', 'length'+total_text);
p.appendChild(input2);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('value', 'Remove');
btn.setAttribute('onclick', 'remove_field("input_text'+total_text+'")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
}
function remove_field(id){
document.getElementById(id+'_wrapper').innerHTML = '';
}
function calculate(){
var answer = 0;
document.getElementById('Result').innerHTML = '';
var inputs = document.querySelectorAll('input[type=text]');
for(var i = 0; i<inputs.length; ){
var length = inputs[i].value;
var width = inputs[i+1].value;
var area = length*width;
i = i + 2;
document.getElementById('Result').innerHTML += 'Answer '+ ++answer +') ' + area + '<br>';
}
}
<div id="wrapper">
<div id="field_div">
<input type="button" value="Add TextBox" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
i have tried a lot of methods but all of them doesn't seem to work.
Really appreciate to those who can help :)
I did not understand your problem with that drop down and your considered logic for it. But I create this below example, which create dynamic select tag, add its options and also calculate a value depend to its value
function createSelect() {
var select = document.createElement("select");
select.id = "height";
var array = [{
title: "method 1",
value: "f1"
},
{
title: "method 2",
value: "f2"
}
];
document.getElementById("wrapper").appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
var p = document.createElement("p");
p.setAttribute("id", "input_text" + total_text + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "length" + total_text);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "length" + total_text);
p.appendChild(input2);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + total_text + '")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
function f1(supposearea) {
return Math.min(
Math.max(2 / -900 * supposearea + 11.7222222222222, 9.5),
11.5
);
}
function f2(supposearea) {
return Math.min(Math.max(2 / -900 * supposearea + 10.2222222222222, 8), 10);
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length;) {
var length = inputs[i].value;
var width = inputs[i + 1].value;
var area = length * width;
i = i + 2;
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + "<br>";
var fId = document.getElementById("height").value;
if (fId == "f1") {
console.log(f1(area));
} else {
console.log(f2(area));
}
}
}
createSelect();
<div id="wrapper">
<div id="field_div">
<input type="button" value="Add TextBox" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
Also you can use official Function constructor. Your code will be like
var array = [
{
title: "method 1",
value: "return Math.min( Math.max(2 / -900 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "method 2",
value: "return Math.min(Math.max(2 / -900 * supposearea + 10.2222222222222, 8), 10);"
}
];
And Usage
var fId = document.getElementById("height").value;
var func = new Function("supposearea", fId);
console.log(func(area));
Full code
function createSelect() {
var select = document.createElement("select");
select.id = "height";
var array = [{
title: "method 1",
value: "return Math.min( Math.max(2 / -900 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "method 2",
value: "return Math.min(Math.max(2 / -900 * supposearea + 10.2222222222222, 8), 10);"
}
];
document.getElementById("wrapper").appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
var p = document.createElement("p");
p.setAttribute("id", "input_text" + total_text + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "length" + total_text);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "length" + total_text);
p.appendChild(input2);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + total_text + '")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length;) {
var length = inputs[i].value;
var width = inputs[i + 1].value;
var area = length * width;
i = i + 2;
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + "<br>";
var fId = document.getElementById("height").value;
var func = new Function("supposearea", fId);
console.log(func(area));
}
}
createSelect();
<div id="wrapper">
<div id="field_div">
<input type="button" value="Add TextBox" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
Update
I think this is your answer
var rowNumber = 0;
function createSelect(tag) {
var select = document.createElement("select");
select.id = "select-" + rowNumber;
var array = [{
title: "10 Grass",
value: "return 1;"
},
{
title: "20 Grass",
value: "return 2;"
},
{
title: "30 Grass",
value: "return 3;"
},
{
title: "40 Grass",
value: "return 4;"
},
{
title: "1",
value: "return Math.min( Math.max(1212 / -243 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "2",
value: "return Math.min(Math.max(23 / 100 * supposearea + 10.2222222222222, 8), 10);"
},
{
title: "3",
value: "return Math.min( Math.max(342 / 50 * supposearea + 11.7222222222222, 9.5), 11.5 );"
},
{
title: "4",
value: "Math.min(Math.max((244/232134*supposearea + 13.7222222222222),11.5),13.5);"
}
];
tag.appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function createSelect1(tag) {
var select = document.createElement("select");
select.id = "select-" + rowNumber;
var array = [{
title: "Original",
value: "0.65"
},
{
title: "10%",
value: "1"
}
];
tag.appendChild(select);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].value;
option.text = array[i].title;
select.appendChild(option);
}
}
function add_field() {
var p = document.createElement("p");
p.setAttribute("id", "input_text" + rowNumber + "_wrapper");
var input1 = document.createElement("input");
input1.setAttribute("type", "text");
input1.setAttribute("class", "input_text");
input1.setAttribute("id", "inp1-" + rowNumber);
p.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "text");
input2.setAttribute("class", "input_text");
input2.setAttribute("id", "inp2-" + rowNumber);
p.appendChild(input2);
createSelect(p);
createSelect1(p);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("onclick", 'remove_field("input_text' + rowNumber + '_wrapper")');
p.appendChild(btn);
document.getElementById("field_div").appendChild(p);
rowNumber++;
}
function remove_field(id) {
document.getElementById(id).innerHTML = "";
calculate();
}
function calculate() {
var answer = 0;
document.getElementById("Result").innerHTML = "";
var ps = document.getElementById('field_div').getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) {
if (ps[i].childNodes.length == 0) continue;
var length = ps[i].childNodes[0].value;
var width = ps[i].childNodes[1].value;
var area = length * width;
var fId = ps[i].childNodes[2].value;
var func = new Function("supposearea", fId);
var discount = ps[i].childNodes[3].value;
var amount = area * (func(area));
document.getElementById("Result").innerHTML +=
"Answer " + ++answer + ") " + area + " ----" + func(area) + '<br>' + amount / discount + "<br>";
}
}
<div id="wrapper">
<div id="field_div">
<input type="button" value="Grass" onclick="add_field();">
</div>
</div>
<p><button type="button" onclick="calculate()">Calculate</button></p>
<p id="Result"></p>
Hope this helps you.

Javascript onclick dynamic for loop get a hold of index

Hello I have a problem gettig a hold of the index in the following code:
Contacts.push("test1 test 4232352");
Contacts.push("test2 test2 5435345");
for(var i = 0; i < Contacts.length; i++){
var res = Contacts[i].split(" ");
var font = document.createElement("FONT");
font.innerHTML = res[0] + " " + res[1];
font.style.marginLeft = "10px";
font.onclick = () => { console.log(i); };
document.getElementById("contacts_collection").appendChild(font);
}
in my mind it should print the index of the element I click on, but instead nomatter which of the 2 I click, it always prints '2'.
The problem is the delclaration of i using the statement var.
An alternative is declaring i using the statement let:
for(let i = 0; i < Contacts.length; i++){}
^^^
Or, you can use IIFE to keep the current value of i:
var Contacts = ["test1 test 4232352", "test2 test2 5435345"];
for (var i = 0; i < Contacts.length; i++) {
var res = Contacts[i].split(" ");
var font = document.createElement("FONT");
font.innerHTML = "<b>" + res[0] + " " + res[1] + "</b>";
font.style.marginLeft = "10px";
font.onclick = ((index) => () => {
console.log(index);
})(i);
document.body.appendChild(font);
}
You can also use the forEach() for your array.
DEMO
In ES5
var Contacts = ["test1 test 4232352", "test2 test2 5435345"],
font = '';
Contacts.forEach(function(v, i) {
v = v.split(" ");
font = document.createElement("FONT");
font.innerHTML = '<b>' + v[0] + ' ' + v[1] + ' </b><br>';
font.setAttribute("style", "margin-left:10px; cursor:pointer");
font.index = i;
font.onclick = function(e) {
console.log(e.target.parentElement.index);
};
document.getElementById('mydiv').appendChild(font);
});
<div id="mydiv"></div>
In ES6
const Contacts = ["test1 test 4232352", "test2 test2 5435345"];
Contacts.forEach((v, i) => {
v = v.split(" ");
let font = document.createElement("FONT");
font.innerHTML = `<b>${v[0]} ${v[1]}</b><br>`;
font.setAttribute("style", "margin-left:10px; cursor:pointer");
font.index = i;
font.onclick = (e => {
console.log(e.target.parentElement.index);
});
document.getElementById('mydiv').appendChild(font);
});
<div id="mydiv"></div>
You can also use for...in statement for array iterates.
DEMO
var Contacts = ["test1 test 4232352", "test2 test2 5435345"],
font = '',v;
for(let i in Contacts){
v = Contacts[i].split(" ");
font = document.createElement("FONT");
font.innerHTML = '<b>' + v[0] + ' ' + v[1] + ' </b><br>';
font.setAttribute("style", "margin-left:10px; cursor:pointer");
font.index = i;
font.onclick = function(e) {
console.log(e.target.parentElement.index);
};
document.getElementById('mydiv').appendChild(font);
};
<div id="mydiv"></div>

getting the variable's value from another funtion

Is there a way to get the 'username' and 'questionid' variable's value in my send() function like how I did with inputText?
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
var username = data[0].username;
//var examid = data[1].examid;
var questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
You do not need var before username and questionid in your renderHTML function, as they have already been defined:
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
username = data[0].username;
//var examid = data[1].examid;
questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);

Cannot remove table after callback function is called

I'm trying to remove a table after some callback functions but table rows just keep getting inserted instead. I don't understand why the table is not being removed after the callbacks. I see that it actually calls the removeTable function and it knows that the table.length is more than 1 but nothing happens. Is it too quick or is it the way I'm doing ajax?
setInterval((function() {
showLeaders();
return showLeaders;
}()), 60000);
function showLeaders() {
uri = 'leaderboard.php'
ajaxLeaders(uri, callback);
setTimeout(function() {
uri = 'leaderboard.php';
ajaxLeaders(uri, callback2);
}, 15000);
}
function removeTable() {
// var table = document.getElementsByTagName('table'), index;
// console.log('im in the removeTable func '+table.length);
// for (index = table.length - 1; index >= 0; index--) {
// table[index].parentNode.removeChild(table[index]);
// }
Array.prototype.slice.call(document.getElementsByTagName('table')).forEach(
function(item) {
item.remove();
// or item.parentNode.removeChild(item); for older browsers (Edge-)
});
}
function ajaxLeaders(uri, callback) {
// console.log('ajaxLoad: ' + uri + ' - ' + params);
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = callback;
request.open("POST", uri, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send();
// clearTimeout(ajax_failed_timer);
// ajax_failed_timer = setTimeout(ajaxError,20000);
}
var nameArray = [];
var totalPointsArray = [];
function callback(evt) {
var tables = document.getElementsByTagName('table');
console.log(tables.length);
if (tables.length >= 1) {
console.log('should remove table cause tables more than 1');
removeTable();
}
if (evt.currentTarget.readyState == 4) {
// console.log(evt.currentTarget.responseText);
var obj = JSON.parse(evt.currentTarget.responseText);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
nameArray.push(obj[key].username);
totalPointsArray.push(obj[key].total_points);
}
}
}
var bottomLeader = '';
var leaderPoints = '';
var leadersTable = '';
leadersTable = document.createElement('table');
var leadersHTML = '';
leadersHTML = '<tr>' +
'<th>Rank</th>' +
'<th>Username</th>' +
'<th>Points</th>' +
'</tr>';
for (var i = 0; i < totalPointsArray.length; i++) {
var rank = i + 1;
var infoBarEle = document.getElementById('info-bar-js');
leadersTable.className = 'animated flipInX';
/// sort width by hightest points
var maxPoints = Math.max.apply(Math, totalPointsArray);
leadersHTML +=
'<tr>' +
'<td>' + rank + '</td>' +
'<td>' + nameArray[i] + '</td>' +
'<td>' + totalPointsArray[i] + '</td>'
'</tr>';
var leaderType = document.getElementById('leaderType');
leaderType.innerHTML = 'Fantasy Football - Weekly Winners';
document.body.className = 'animated slideInRight';
}
leadersTable.innerHTML = leadersHTML;
insertAfter(leadersTable, infoBarEle);
function callback2(evt) {
var tables = document.getElementsByTagName('table');
if (tables.length >= 1) {
removeTable();
}
if (evt.currentTarget.readyState == 4) {
// console.log(evt.currentTarget.responseText);
var obj = JSON.parse(evt.currentTarget.responseText);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
nameArray.push(obj[key].username);
totalPointsArray.push(obj[key].total_points);
}
}
}
var bottomLeader = '';
var leaderPoints = '';
var leadersTable = '';
leadersTable = document.createElement('table');
var leadersHTML = '';
leadersHTML = '<tr>' +
'<th>Rank</th>' +
'<th>Username</th>' +
'<th>Points</th>' +
'</tr>';
for (var i = 0; i < totalPointsArray.length; i++) {
var rank = i + 1;
var infoBarEle = document.getElementById('info-bar-js');
leadersTable.className = 'animated flipInX';
/// sort width by hightest points
var maxPoints = Math.max.apply(Math, totalPointsArray);
leadersHTML +=
'<tr>' +
'<td>' + rank + '</td>' +
'<td>' + nameArray[i] + '</td>' +
'<td>' + totalPointsArray[i] + '</td>'
'</tr>';
var leaderType = document.getElementById('leaderType');
leaderType.innerHTML = 'Fantasy Football - Season Winners';
document.body.className = 'animated slideInRight';
}
leadersTable.innerHTML = leadersHTML;
insertAfter(leadersTable, infoBarEle);
}
//insertAfter function
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

Categories