Google Chrome Local Storage Adding Links - javascript

So I'm trying to add an option on my options page for people to set 1-3 letters as a link to a website. Currently I'm getting a NaN value for the linkNumber when I run the function.
The Function:
function addLink () {
chrome.storage.local.get('linkNumber', function (x) {
if (x.linkNumber == undefined) {
chrome.storage.local.set({'linkNumber': '0'}, function() {
addLink();
});
} else {
var linkNumberInteger = parseInt(x.linkNumber);
var handle = document.getElementById("short");
var link = document.getElementById("long");
var handleValue = handle.value;
var linkValue = link.value;
var handleNumber = x.linkNumber + '-handle';
var urlNumber = x.linkNumber + '-link';
var objectOne = {};
var objectTwo = {};
objectOne[handleNumber] = x.linkNumber + '-handle';
objectTwo[urlNumber] = x.linkNumber + '-link';
console.log(x.linkNumber);
console.log(handleNumber);
chrome.storage.local.set({handleNumber: handleValue}, function(y) {
console.log(y.handleNumber + ' handle saved');
});
chrome.storage.local.set({urlNumber: linkValue}, function(z) {
console.log(z.handleNumber + ' link saved');
});
var linkNumberIntegerNext = linkNumberInteger++;
var n = linkNumberIntegerNext.toString();
chrome.storage.local.set({'linkNumber': n}, function() {
});
alert('Link Added');
}
});
}
The Html:
<h3 class="option">Add Quick Link:</h3>
<input contenteditable="true" type="text" class="short-quicklink" id="short" maxlength="3">
<span>http://</span><input contenteditable="true" type="text" class="long-quicklink" id="long">
<button class="add">Add Quick Link</button>

Related

html not appending to the carousel on popover

I Am Trying to make a popover with a bootstrap carousel and where the carousel items are to be generated and appended from a script but I get the carousel but I am unable to append the item. I tried hard but I didn't come up with a solution.
the HTML initialized is as below
HTML:
<div class="popup" data-popup="popup-1">
<div class="popup-inner">
<i class="fas fa-bars"></i>
<div class="frame">
<div id='carousel' class='carousel slide' data-bs-ride='carousel'>
<div class='carousel-inner items-slider1'>
</div>
</div>
</div>
</div>
</div>
the script I have tried was
Javascript:
function findallchord(currentchord , currenttype) {
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord ,currenttype,i)) {
Raphael.chord("div3", Raphael.chord.find(currentchord , currenttype,i), currentchord +' ' +currenttype).element.setSize(75, 75);
}
}
}
var getChordRoots = function (input) {
if (input.length > 1 && (input.charAt(1) == "b" || input.charAt(1) == "#"))
return input.substr(0, 2);
else
return input.substr(0, 1);
};
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
});
I have also tried appendTo also as
$(theDiv).appendTo('.items-slider1');
Please Help to solve this
This is the output I get, the appended elements are not in the carousel
Note: I am using Bootstrap 5
Try instantiating the carousel after you've set it up
/*
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
*/
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
$('.carousel-inner').carousel();
});
It was needed to do call the click function first before popover as below
$('[data-bs-toggle="popover"]').click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
}).popover({
html: true,
content: function() {
return $('.popup').html();
}});

JavaScript arrays adding last element instead of recently added input

Good evening. I am new to JavaScript and I need help with my mini-project and I have only one issue here and it is in the this.Add = function ().
It works properly when I enter a duplicate value from my list therefore it displays an alert that no dupes are allowed. But... when I enter a unique value, it only adds up the last element present (Wash the dishes) from myTasks list. instead of the one I recently entered and the list goes on adding the same ones. Did I just misplace something?
This is my final activity yet and I want to finish it to move to the next function. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tasks CRUD</title>
<style>
#tasks{
display: none;
}
</style>
</head>
<body>
<center>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-task" placeholder="Add another card">
<input type="submit" value="Add">
</form>
<div id="tasks" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-task">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Name</th>
</tr>
<tbody id="myTasks">
</tbody>
</table>
</center>
<script>
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
if (task ) {
for(task of this.myTasks)
{
var ctr = 0;
if(document.getElementById("add-task").value == task){
ctr = 1;
break;
}
}
if(ctr == 1)
{
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task.trim());
// Reset input value
el.value = '';
// Dislay the new list
this.FetchAll();
}
}
};
this.Edit = function (item) {
var el = document.getElementById('edit-task');
// Display value in the field
el.value = this.myTasks[item];
// Display fields
document.getElementById('tasks').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
// Get value
var task = el.value;
if (task) {
// Edit value
self.myTasks.splice(item, 1, task.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item) {
// Delete the current row
this.myTasks.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput() {
document.getElementById('tasks').style.display = 'none';
}
</script>
</body>
</html>
In your for loop:
for (task of this.myTask) {
}
You are not declaring a new task variable, but instead assigning to the outer task variable, hence the repeated addition of tasks already in your list.
You can declare a new variable in the for scope like so:
for (const task of this.myTask) {
}
Your HTML as it is.
And your Javascript goes like below. You have a bug while checking if the task already exists in the array. As you're comparing string value either use simple for loop with triple equals or do as i have attached below.
var app = new function() {
this.el = document.getElementById('myTasks');
this.myTasks = ['Clean the bathroom', 'Wash the dishes'];
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'task';
if (data) {
if (data > 1) {
name = 'Things To DO';
}
el.innerHTML = data + ' ' + name ;
} else {
el.innerHTML = 'No ' + name;
}
};
this.FetchAll = function() {
var data = '';
if (this.myTasks.length > 0) {
for (i = 0; i < this.myTasks.length; i++) {
data += '<tr>';
data += '<td>' + this.myTasks[i] + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(this.myTasks.length);
console.log(this.myTasks.length);
return this.el.innerHTML = data;
};
this.Add = function () {
el = document.getElementById('add-task');
// Get the value
var task = el.value;
console.log(task);
if (task ){
var arrayContainsTask = (this.myTasks.indexOf(task) > -1);
if(arrayContainsTask == true){
window.alert("Duplicates not allowed.");
}else{
// Add the new value
this.myTasks.push(task);
// Reset input value
el.value = '';
}
// Dislay the new list
this.FetchAll();
}
}
}

Store text from dynamically created textareas in localStorage

Problem - I have 2 buttons addNew and submitText. I have created a javascript function for each of these two buttons. The addNewcreates textareas with unique ids (note0, note1...). The submitText is supposed to submit the text from all the dynamically created textareas in localStorage in the (key, value) format (notesList0, data), (notesList1, data) and so on. The code is as follows -
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
} , false);
});
The addNew works but submitText only saves value of the first textarea. Where am I going wrong?
I guess it's because of flag staying "false" after the first loop:
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
flag = true;
}
} , false);
});
Use the following for the submit function to make it work for dynamically created elements:
$(document).on("click", "#submitText", function(){
// Do stuff
})
Make sure the ID is only used once on the page. Otherwise switch to class definition.
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
for(counter=0; counter<=note_id; counter++) {
var flag=true;
var textData = $("#note"+counter).val();
if(textData != undefined && textData != '') {
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
}
} , false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="addNew">Add new</span>
<span id="submitText">Submit</span>
<div id="textFields"></div>
In case you get error when executing the code, check this link:
Failed to read the 'localStorage' property from 'Window'

How to obtain one by one in IndexedDB

I am trying to obtain, one by one, the elements in IndexedDB. My target is:
Obtain the first element[key].verbo and adjetivo and sustativo and print in html, to see in the web.
Wait to the user insert a one sentence in what includes these words and click check.
Obtain the second element[key].verbo and adjetivo and sustativo and print in html, to see in the web.
The same as 2.
And continue in the same way.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexedDB: Local Database with HTML5</title>
<script type="text/javascript">
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var dataBase = null;
var pulsador = false;
function startDB() {
dataBase = indexedDB.open('db', 1);
dataBase.onupgradeneeded = function (e) {
var active = dataBase.result;
var object = active.createObjectStore("people", {keyPath: 'id', autoIncrement: true});
object.createIndex('by_adjetivo', 'adjetivo', {unique: false});
object.createIndex('by_verbo', 'verbo', {unique: true});
};
dataBase.onsuccess = function (e) {
alert('Base de datos cargada');
loadAll();
};
dataBase.onerror = function (e) {
alert('Error al cargar Base de datos');
};
}
function add() {
var active = dataBase.result;
var data = active.transaction(["people"], "readwrite");
var object = data.objectStore("people");
var request = object.put({
verbo: document.querySelector("#verbo").value,
adjetivo: document.querySelector("#adjetivo").value,
sustantivo: document.querySelector("#sustantivo").value
});
request.onerror = function (e) {
alert(request.error.adjetivo + '\n\n' + request.error.message);
};
data.oncomplete = function (e) {
document.querySelector('#verbo').value = '';
document.querySelector('#adjetivo').value = '';
document.querySelector('#sustantivo').value = '';
alert('Object successfully added');
loadAll();
};
}
function loadAll() {
var active = dataBase.result;
var data = active.transaction(["people"], "readonly");
var object = data.objectStore("people");
var elements = [];
object.openCursor().onsuccess = function (e) {
var result = e.target.result;
if (result === null) {
return;
}
elements.push(result.value);
result.continue();
};
data.oncomplete = function () {
var outerHTML = '';
for (var key in elements) {
v=elements[key].verbo;
outerHTML+='\n\ <tr>\n\<td>'
+"\t"+"Verbo: \t"+ elements[key].verbo + '</td>\n\<td>'
+"\t"+"Adjetivo: \t"+ elements[key].adjetivo + '</td>\n\ <td>'
+"\t"+"Sustantivo: \t"+ elements[key].sustantivo
+ '</td>\n\ </tr>';
document.querySelector("#elementsList").innerHTML = outerHTML; // I want print one verbo,adjetivo and sustantivo
gradeTest(elements[key].verbo,elements[key].adjetivo,elements[key].sustantivo); //Before, i want
}
elements = [];
};
}
function gradeTest(p1,p2,p3) {
var a1 = document.getElementById('q1').value.toLowerCase();
if(a1.includes(p1) )
if (a1.includes(p2))
if (a1.includes(p3)) {
alert('They are equal');//and we can continue to two elements[key].
}
}
</script>
</head>
<body onload="startDB();">
<input type="text" id="verbo" placeholder="Enter verbo" />
<input type="text" id="adjetivo" placeholder="Enter adjetivo" />
<input type="text" id="sustantivo" placeholder="Enter sustantivo" />
<button type="button" onclick="add();">Save</button>
<hr>
<div id="elements">
<table>
<caption>g</caption>
<thead>
<tr>
<th>Verbo</th>
<th>Adjetivo</th>
<th>Sustantivo</th>
</tr>
</thead>
<tbody id="elementsList">
<tr>
<td colspan="3">Not elements to show</td>
</tr>
</tbody>
<tr>
<td>introduce one verb,adjetive and sustantive</td>
<td><input name="q1" type="text" id="q1" size="30" maxlength="30"/></td>
</tr>
<tr>
<td><input name="submit" type="button" onClick="gradeTest()" value="check"/></td>
</tr>
</table>
</div>
Try creating an array of the items before hand and using a global variable to track the position in the items array. For example:
// Declare a global variable to hold the items
var items = [];
// Open a connection and query for items
function fillItems() {
var openRequest = indexedDB.open('mydb, 1);
openRequest.onsuccess = onOpenConnection;
}
// Query the store for all items
function onOpenConnection(openRequestEvent) {
if(openRequestEvent.type !== 'success' ) {
console.log('connection error');
return;
}
var connection = openRequestEvent.target.result;
var transaction = connection.transaction('mystorename');
var store = transaction.objectStore('mystorename');
var request = store.openCursor();
request.onsuccess = addNextItemFromDatabase;
}
// Add the item at the cursor's current position to the items array,
// and then request the cursor to advance by 1
function addNextItemFromDatabase(event) {
var cursor = event.target.result;
if(cursor) {
items.push(cursor.value);
cursor.continue();
}
}
// When page is loaded, fill the items array
fillItems();
// Global variable that keeps track of index into items array
var currentItemPosition = -1;
// Get the button the user clicks
var button = document.getElementById('mybutton');
// Attach a click listener function that is called whenever the
// button is clicked
button.onclick = function(event) {
// Increment the current position by 1 each time the button
// is clicked
currentItemPosition = currentItemPosition + 1;
// Check if in bounds
if(currentItemPosition >= items.length) {
console.log('out of bounds');
return;
}
// Get the item at the current position
var currentItem = items[currentItemPosition];
console.log(currentItem.verbo);
console.log(currentItem.adjectivo);
// etc..
};

Javascript 2 clicks onclick

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Use javascripts' setTimeout( function() {})
You could do something like this (sudo code below. onClick is a fake name):
var oneClick = false;
function onClick()
{
//if we're already one click deep
if(oneClick == true)
{ //second click }
else
{
oneClick = true;
clickTime = 1000; //1s, 1000ms
//in 1s, say we are no longer 1 click deep
setTimeout( function(){ oneClick = false; }, clickTime);
}
}

Categories

Resources