How to keep appended data on refresh? - javascript

I have a contenteditable div that serves as an editor to allow users to input and save text. Upon clicking a save button, I prompt them to ask what they want to save the text as.
The title is then saved to localstorage and appended to a separate div, where they click the title and the text they saved it under will appear in the editor.
The issue now is that whenever I refresh the page, the appended data disappears. Was wondering how I could keep the appended data there on refresh? Also, I need it to still be able to link to its content, not just become a bunch of text in a div.
I've simplified the entire code here:
<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>
</head>
<body>
<div style="width:10em; height:10em; border-style:solid; border-color:black;" id="editor1" contenteditable="true"></div>
<button id="savebtn">Save Changes</button>
<div style="width:10em; height:5em; border-style:solid; border-color:red;" id="Contentable"></div>
<script>
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
titles = localStorage.getItem("titles");
if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.innerHTML;
localStorage.setItem("userEdits", userVersion);
editElem.innerHTML = "";
});
});
function showData(txt) {
editElem.innerHTML = localStorage.getItem(txt);
}
</script>
</body>
</html>
EDIT: How can I also remove the data from the div using say a "remove" button? In the event where the div gets too packed and there are some useless titles that the user wants the remove.

Try this ... i hope it works
<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>
<style type="text/css">
.selected{
background-color: blue;
color:white;
}
</style>
</head>
<body>
<div style="width:10em; height:10em; border-style:solid; border-color:black;" id="editor1" contenteditable="true"></div>
<button id="savebtn">Save Changes</button>
<button id="remove">Remove Data</button>
<div style="width:10em; height:5em; border-style:solid; border-color:red;" id="Contentable"></div>
<script>
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML);
titles = localStorage.getItem("titles");
if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.innerHTML;
localStorage.setItem("userEdits", userVersion);
editElem.innerHTML = "";
});
});
function showData(txt) {
editElem.innerHTML = localStorage.getItem(txt);
}
function loadData()
{
var htmlData=localStorage.getItem("titles");
htmlData=htmlData.replace(/\[|\]/g, "");
htmlData=htmlData.replace(/["']/g, "")
htmlData=htmlData.split(",");
var arlength=htmlData.length;
console.log(arlength)
for(num=0;num<arlength;num++)
{
$("#Contentable").append("<a onclick=showData('" + htmlData[num] + "')>" + htmlData[num] + "</a><br>");
}
}
loadData();
var selected;
$("#Contentable a").click(function(){
selected=$("#Contentable a").index(this);
$("#Contentable a").removeClass("selected")
$(this).addClass("selected");
})
$("#remove").click(function(){
$("#Contentable a:eq("+selected+")").remove();
// Some Delete codes to localStorage here=================================
})
</script>
</body>
</html>

Related

Why is my save function not executing in its entirety?

I am trying to create a to-do list in HTML, CSS and pure JS.
const dSubmit = document.getElementById('submit');
const storeData = [];
let typer = document.getElementById('type');
let input = document.getElementById('text');
const list = document.getElementById('listHolder');
dSubmit.addEventListener("click", (e) => {
e.preventDefault();
if (input.value == "") {
typer.innerHTML = "Please enter a task";
} else {
typer.innerHTML = "";
store();
}
});
function store() {
const tData = document.getElementById('text').value;
storeData.push(tData);
updater();
input.value = "";
}
function deleter (index) {
storeData.splice(index, 1);
updater();
}
function updater() {
let htmlCode = "";
storeData.forEach(function(item, index){
htmlCode += "<div class='test'><div id = "+ index +">" + item + "</div><div class='sideBtn'><button type='button' class='edit' onClick= 'editF("+ index +")'>Edit</button><button class='delBtn' onClick= 'deleter("+ index +")'>Delete</button> </div> </div>"
})
list.innerHTML = htmlCode;
}
function editF (index) {
let tempOne = document.getElementById(index);
let tempTwo = "<input id='inputText"+String(index)+"' type='text' name='task' value ='" + String(storeData[index]) + "'><button id='saveText"+String(index)+"' onClick= 'save("+index+")' >Save</button>"
tempOne.innerHTML = tempTwo;
}
function save (index) {
console.log('test1')
let tempOne= document.getElementById('saveText'+String(index));
let tempTwo = document.getElementById('inputText'+String(index));
console.log('test2')
tempOne.addEventListener("click", function foo (){
console.log('test3')
storeData.splice(index,1,tempTwo.value)
updater()
}
)
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>To Do List</title>
</head>
<body>
<h1>To-do-list</h1>
<form>
<label for="task">Please enter item:</label>
<input type="text" name="task" id="text">
<button id="submit">Submit</button>
</form>
<div id='type'></div>
<div>List:</div>
<div id="listHolder" class="test"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
I am facing problems with the save function. If I edit an item in the to-do list and click the save button, the function executes up to the point of console.log('test2'). If I click save again the function executes in its entirety.
I would like to ask why the first click results in execution of the save function up to 'test2'?
Additionally would anyone be kind enough to critique my JS? are there things in dire need of improvement? or is there a more practical/efficient method of writing my JS code?
Thank you for your help in advance.
After the 'test2' log, you are adding an event listener, and the rest of the code is inside of the listener block. The code in the listener block is only executed once that listener receives a 'click' event, which is why it works the second time.

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

Bold selection of a textbox with click of a button

I currently have this code: https://jsbin.com/hocisirovo/edit?html,css,js,output
With the button, it bolds the entire text in the text box. How can I bold only what I select in the text box? The easy way would be to use execCommand but I cannot use that.
Any help is appreciated.
Thanks!
I didn't quite get your question but you could use an editable div to make parts of your text bold.
<html>
<head>
<script>
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
function boldSelected(){
var textBox = document.getElementById("textbox");
var text = textBox.innerHTML;
var boldText = getSelectionText();
var offset1 = text.indexOf(boldText);
var offset2 = offset1 + boldText.length;
var str1 = text.substring(0,offset1);
var str2 = text.substring(offset2,text.length);
textBox.innerHTML=str1+"<b>"+boldText+"</b>"+str2;
}
function undoBold(){
if(document.getElementById("textbox").innerHTML == "<b></b>")
document.getElementById("textbox").innerHTML == "";
}
</script>
</head>
<body>
<div onkeypress="undoBold()" contentEditable="true" id="textbox" style="width:30%; border:1px solid #0a0a0a;padding:3px;"></div></br>
<button onclick="boldSelected()">Bold</button>
</body>
</html>

How can I run a function when a radio is selected and I click a button?

I've created this simple code that I'll use to store in the user's browser, so, I'd like to know how can I run a function when there's a selected radio and when I click the delete button, using JS or JQuery. Any help is appreciated.
Thanks in advance.
check it on liveweave
P.S.: Your browser should have WebStorage support
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de"+ taskCounter;
for(var i=1;i<taskCounter;i++){
var temp = "de" + i;
document.writeln("<br/>"+'<input type="radio" name="rad" value="'+localStorage.getItem(temp)+'" /> <label>'+localStorage.getItem(temp)+'</lable>');
}
function saveItUp(){
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp(){
$('input:radio').selected(function(){
if (this.checked) {
alert(this.value);
}
});
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label> <textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
I have edited your snippet. Use $('input[type="radio"]').prop('checked') to see whether the radio button is checked. You will need to modify the selector to get the appropriate radio button if there are multiple on the page.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + localStorage.getItem(temp) + '" /> <label>' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp() {
if ($('input[type="radio"]').prop('checked')) {
alert('Deleting!');
} else {
alert('Delete radio not checked!');
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
<input type="radio">Check to delete
</div>
</body>
</html>
I've been trying other ways to achieve it, and I found a nice way that gave me the expected result, thank all of you who tried to help me.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + temp + '" /> <label>' + 'Code: ' + temp + ' | Value: ' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
var selectedRadioId = 0;
$('input:radio').change(function() {
if (this.checked) {
selectedRadioId = this.value;
}
});
function deleteItUp() {
if (selectedRadioId !== 0) {
alert('Deleting!');
} else {
alert("Radio hasn't been checked!");
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
You are talking about firing an event when a radio button is checked and then calling a callback function: https://api.jquery.com/checked-selector/

how can i retrieve a current value of textarea?

Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>

Categories

Resources