Remove quotes from string that is imported from localStorage - javascript

I'm creating a front-end page where user can create textarea by pressing a button and then save the information in the localStorage. When the load button is pressed, the same number textareas appear and their content comes from the localStorage. The problem is that when I retrieve the info from the localStorage, the value has "", which I want to remove.
I have tried replace(/"([^"]+(?="))"/g, '$1');
i = localStorage.getItem('AllNum');
// Allnum is the is where the generated textareas are placed
function add() {
//i represents the number of textareas
i++;
$('#alltxt').append('<div class="textarea"><input></input><textarea id="txt' + i + '"></textarea></div>');
}
function save() {
for (var a = 1; a <= document.getElementById("alltxt").childElementCount; a++) {
localStorage.setItem("txt" + a, document.getElementById('txt' + a).value);
}
localStorage.setItem('AllNum', i);
}
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea"><input></input><textarea id="txt' + i + '">"' + invert(i) + '"</textarea></div>');
}
}
}
function invert(i) {
var a = localStorage.getItem('txt' + i);
a = a.replace(/"([^"]+(?="))"/g, '$1');
return a;
}
https://codepen.io/abooo/pen/RvbOzV?editors=1010
To test the code generate some textareas, then enter some values in them and press +. After this reload the page. Finally click Load button. You can see that 123 changed into "123"

The problem is that you have "" around the text you are putting in.
In your load function, change "' + invert(i) + '" to ' + invert(i) + ' (Remove the two ").

Related

Add new line using jQuery concat

Through ajax response I'm passing array data from controller to blade.
On Ajax success I'm looping through array with 2 elements and concatenating string to display later on in my bootstrap popover.
success: function (data) {
var content = "";
var num = 1;
for (var i = 0; i < data.length; i++) {
content = content.concat(num + "." + " " + data[i]);
num++;
}
$("#content").popover({content: content});
}
Result:
I would like to add new line, so that each item or "artikel" would be displayed in new line e.g. :
1.Artikel...
2.Artikel...
I tried to add "\n" (as below) or html break but nothing works, it only appends as string.
content = content.concat(num + "." + " " + data[i] + "\n");
Use this:
content.concat(num + "." + " " + data[i] + "<br/>");
And this:
$("#content").popover({ html:true, content: content });

Display element of array onclick

This code displays the content of JSON file by formatting every word into sentences and then into HTML. On mouseover, words become blue. On click they become red. The next thing I want to do is to display the translation of the words (already in the json array) onclick.
https://jsfiddle.net/ve64qvtm/
var json = [
[
["Peki", "Well"],
["nedir", "what"],
["bu", "it"],
...
]
];
var arr2 = [];
for (k = 0; k < json.length; k++) {
var arr = json[k];
arr2.push('<p>');
for (i = 0; i < arr.length; i++) {
if (arr[i][0].length == 1) {
arr2.push(arr[i][0]);
} else {
arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
}
}
arr2.push('</p>');
}
document.getElementById("text").innerHTML = arr2.join('');
var words = [...document.getElementsByClassName("word")];
words.forEach(function(word) {
word.onclick = function() {
if (word.className == "clicked") {
word.className = 'notclicked';
}
if (word.className == "onmouse") {
word.className = 'clicked';
}
}
word.onmouseover = function onMouse() {
if (word.className != "clicked") {
word.className = 'onmouse';
}
}
word.onmouseout = function onMouse() {
if (word.className != "clicked") {
word.className = 'notclicked';
}
}
});
I have no idea how to do this as the text to display is a variable.
How am I supposed to do this?
How about using Twitter Bootstraps tooltip. Add jQuery, bootstraps JS and CSS; once all this is added you would need to edit the line
arr2.push(' <span class="notclicked word ' + i + '">' + arr[i][0] + '</span>');
To something like
arr2.push(' <span class="notclicked word ' + i + '" data-toggle='tooltip' data-placement='top' title='YOUR_TRANSLATION_HERE'>' + arr[i][0] + '</span>');
EDIT 2 - Updated Link:
Here is a working example
Edit 3
I Would also add a bit of margin on top and bottom so that you donĀ“t get unexpected behaviour from the tooltips, just because there is no space.

making a loop to display buttons

I am trying to make a loop that will display some images and add an event listener to each image which, when clicked will assign the appropriate value to humanGoal. I have:
var humanGoal;
function displayPicker(round){
for(var i = 0; i <= round; i++){
document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
document.getElementById('picker'+i).addEventListener("click", function () {
humanGoal = i;
document.write('you picked ' + humanGoal );
});
}
}
why does humanGoal always === round+1, instead of the variable i from the for loop?
The humanGoal variable is being overwrited with every for loop iteration and holds the round + 1 value at the end. Different words speaking - it will always display a wrong index.
Solution: apply same class to the each img element, bind a click event listener and display the actual index by passing i variable inside the Array#forEach function.
function displayPicker(round){
for (var i = 0; i <= round; i++){
document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '" class="img">');
}
var elems = document.getElementsByClassName('img');
Array.from(elems).forEach((v,i) => v.addEventListener('click', function() {
console.log(`You picked ${i}`);
}));
}
displayPicker(5);
See answer to your question is simple, when you were trying to assign human goal with value of i, the loop is already been iterated over "rounds" value that why you always getting i === round inside click function.
See the below code snippet,
<html>
<script>
var humanGoal;
function displayPicker(round){
for(var i = 0; i <= round; i++){
document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
document.getElementById('picker'+i).addEventListener("click", function () {
console.log("me getting called second");
humanGoal = i;
document.body.append('you picked ' + humanGoal );
});
console.log("me getting called first");
}
}
</script>
<body onload="displayPicker(4)">
</body>
</html>
for getting the correct result you can follow the approach provided by #Kind user

Unable to use jquery ajax to get sound file due to cross origin access control

I seem to be unable to check if a audio file exists before it actions anything due to No Access-Control-Allow-Origin'.
Is it possible to have this and if so, how ?
pText[n] = any word, for example: and, about.
But googles API do not hold names, so I need to check if a name is added to the text, and if so, use a different source url.
// audio check
var audioCheck = $.get('https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3');
console.log(audioCheck);
I have also tried $.ajax but without success.
This is the full script so you can see what I am doing
function populate(pText) {
for(var n=0; n < pText.length; n++) {
// audio check
var audioCheck = $.get('https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3');
console.log(audioCheck);
// if(audioCheck) { link is live } else { link is 404 }
//console.log(pText[n]);
$('[name=p1_1]').append('<span id="s' + n + '"><audio id="a' + n + '" src="https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3" type="audio/mpeg"></audio>' + pText[n] + '</span> ');
}
}
And help would be appreciated :)
I have managed to resolve this using the simple method of onerror
Here is the full code :)
function populate(pText) {
var tex = '';
for(var n=0; n < pText.length; n++) {
//console.log(pText[n]);
tex += '<span id="s' + n + '"><audio id="a' + n + '" src="https://ssl.gstatic.com/dictionary/static/sounds/de/0/' + pText[n] +'.mp3" onerror="mediaerro(' + n + ',"' + pText[n] +'")" type=audio/mpeg"></audio>' + pText[n] + ' </span>';
}
$('[name=p1Text]').html(tex);
}
$(document).on("click", "span", function() {
$(this).find('audio')[0].play();
});
mediaerro = function(id, word) {
console.log(word);
switch(word) {
case "Rocko":
$('#a' + id).attr('src', 'http://domain.com/books/book1/words/rocko.mp3');
break;
case "Caroline":
$('#a' + id).attr('src', 'http://domain.com/books/book1/words/caroline.mp3');
break;
case "Benji":
$('#a' + id).attr('src', 'http://domain.com/books/book1/words/benji.mp3');
break;
}
};
Using the dynamic audio id and managed to create a function based on an error, which replaces the broken link with a new one where the new recording is. Works a treat!

Using append() doesn't replace previous content

Firstly, I was trying to replace some contents in a div container using html() in Javascript on click. The problem using this approach is it only put the last value in the array.
So, I used append() instead. But it doesn't work like what I have expected. Well, it does append text in the for loops, but after a click, it just appends the content without removing the previous content like what html() does.
Here is how I implement it:
<div id="events-content"></div>
// using Responsive Calendar js
onMonthChange: function(events) {
for (var eventsDate in options.events) {
if (eventsDate.indexOf(monthKey) != -1) {
var monthEvents = options.events[eventsDate];
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
$('#events-content').append(
'<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>');
}
}
}
},
...
How do I replace the previous appended text using Javascript?
I'm using this in Responsive Calendar JS
well, you could do something like this...
Prepare all the markup in the loop.
var html = "";
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
html += '<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>';
}
$('#events-content').html(html);
Clear the html before the for loop/append mechanism.
Use .empty()
onMonthChange: function(events) {
$('#events-content').empty() //or $('#events-content').html('');
for (var eventsDate in options.events) {
if (eventsDate.indexOf(monthKey) != -1) {
var monthEvents = options.events[eventsDate];
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
$('#events-content').append(
'<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>');
}
}
}
},

Categories

Resources