My code, upon click on "produce", takes words from a text area, loops, and concatenates the way I need it.
All's good, all is working.
BUT
if I press "Clear" and click "produce" again, my code inserts the looped words twice.
Question: How can I always get the same result everytime I click "produce"?
jsfiddle
HTML:
<textarea id="KWarea" rows="4" cols="50">*casio*
*citizen*
*clarks*
</textarea>
<br>
<button id="produce">produce</button>
<button id="clear">clear</button>
<br />
<br />
<div id="result"></div>
<br />
<br />
<br />
<div id="result">
Expected result example:
<br />
("*casio*","* casio *", "*citizen*", "* citizen *", "*clarks*", "* clarks *")
</div>
jQuery:
$(document).ready(function () {
var endString = "";
$('#produce').click(function () {
var myTxtArea = document.getElementById('KWarea');
myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');
var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
for (var i = 0; i < lines.length; ++i) {
endString += '"*' + lines[i] + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
// console.log(lines[i]);
}
var trimmedStr = endString.slice(0, -1);
$('#result').html("Here is the final string:( " + trimmedStr + ")");
});
$('#clear').click(function () {
$('#result').empty();
});
});
You are appending string without emptying it first, try this:
$(document).ready(function () {
var endString = "";
$('#produce').click(function () {
var myTxtArea = document.getElementById('KWarea');
myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');
var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
endString ='';
for (var i = 0; i < lines.length; ++i) {
endString += '"*' + lines[i] + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
// console.log(lines[i]);
}
var trimmedStr = endString.slice(0, -1);
$('#result').html("Here is the final string:( " + trimmedStr + ")");
});
$('#clear').click(function () {
$('#result').empty();
});
});
The reason this is happening is because you have endString as a global variable. To fix this put
var endString = "";
Inside of $('#produce').click(function () {
like so
$(document).ready(function () {
$('#produce').click(function () {
var endString = "";
var myTxtArea = document.getElementById('KWarea');
myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, '');
var lines = $('#KWarea').val().replace(/\*/g, '').split('\n');
for (var i = 0; i < lines.length; ++i) {
endString += '"*' + lines[i] + '*"' + ',' + '"* ' + lines[i] + ' *"' + ',';
// console.log(lines[i]);
}
var trimmedStr = endString.slice(0, -1);
$('#result').html("Here is the final string:( " + trimmedStr + ")");
});
$('#clear').click(function () {
$('#result').empty();
});
});
Related
This simple code is supposed to give an alert when the button is pressed the amount of times you wrote in the input. There is no error or something but the code just doesn't work. Am I stupid and did I miss something or is the logic of my code just wrong? and how do make it work?
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button(){
text1 = document.getElementById("number").value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check(){
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2){
alert(correct + '/' + text2);
}
function wait(){
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id = 'but'> ok </button>
<div id = 'div'> </div>
The .value returns a string and you must convert it into a number (if you want to) before using it.
So in line 6 do this:
text1 = Number(document.getElementById("number").value);
and also in the check() function:
text2 = Number(document.getElementById('questions').value);
Hope that works.
I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
function pick(n) {
return n[Math.floor(Math.random() * n.length)];
}
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.
You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
if (this.length < 1) throw "Cannot get random value from zero-length array";
var randomIndex = Math.floor(Math.random() * this.length);
var randomValue = this[randomIndex];
if (removeItem)
this.splice(randomIndex, 1);
return randomValue;
};
function constructDescription(sentenceCount) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var description = "";
for(var i = 0; i < sentenceCount; i++) {
if (body.length > 0 && adj.length > 0 && word.length > 0) {
description += (description.length > 0) ? " And your " : "Your ";
description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
}
}
return description;
}
Try it out with a Fiddle here.
Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = ''
function pick(n) {
var idx = Math.floor(Math.random() * n.length);
var str = n[idx];
n.splice(idx, 1)
return str;
}
function getPhrase(i) {
var phrase = pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
return i == 0 ? "Your " + phrase : " And your " + phrase;
}
for (var i = 0; i < times; i++) {
str += getPhrase(i);
}
return str;
}
document.body.innerHTML = go(4);
You just need to combine your splice and your randomizer. example:
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function pick(n) {
return n.splice(Math.floor(Math.random() * n.length), 1);
}
var str = "";
for (var i = 0; i < times; i++) {
str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
}
return str;
}
#lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function go(times) {
function pick(n) {
var index = Math.floor(Math.random() * n.length)
var randomString = n[index];
n.splice(index,1);
return randomString;
}
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
console.log(go(2));
Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}
So I'm basically making an savings account system. A user can set up an account and start with a balance of 0 the withdraw and deposit money whenever they want. It works perfectly the first few times but then it gives me the RangeError either when I try logging in or out.
setScreen('LogIn');
var balance;
var curbal = [];
var totalAccts=[];
onEvent("saveAcct", "click", function() {
var username = getText('createUserInput');
var password = getText('createPassInput');
appendItem(totalAccts, getText('createUserInput') + " " +
getText('createPassInput') + " ");
console.log("Username: " + username + " Password: " + password);
console.log(totalAccts);
setScreen('LogIn');
});
onEvent('makeAcct', 'click', function(){
setScreen('CreateAcct');
setText('createUserInput', "");
setText('createPassInput', "");
setText("userInput", "");
setText("passInput", "");
hideElement('alert');
});
onEvent('addMoney', 'click', function(){
setNumber('balance', balance + getNumber('addInput'));
balance = balance + getNumber('addInput');
setNumber('addInput', '');
console.log(balance);
});
onEvent('subMoney', 'click', function(){
setNumber('balance', balance - getNumber('subInput'));
balance = balance - getNumber('subInput');
setNumber('subInput', '');
console.log(balance);
});
onEvent('login', 'click', function(){
balance = 0;
changeEnBal(totalAccts, curbal);
});
onEvent('logout', 'click', function(){
changeExBal(totalAccts, getNumber('balance'), curbal);
hideElement('alert');
setText('balance', 0);
setText("userInput", "");
setText("passInput", "");
setScreen('LogIn');
});
onEvent("goBack", "click", function() {
setScreen('LogIn');
});
function changeEnBal(list, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
setScreen('Account');
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balance = balList[a];
setNumber('balance', balList[a]);
setScreen('Account');
console.log(balList[a]);
}
}
}
}
for (var b = 0; b < balList.length; b++) {
if (balList[b] != (user + " " + pass + " " + balList[b])){
showElement('alert');
}
}
}
function changeExBal(list, curBal, balList) {
var user = getText('userInput');
var pass = getText('passInput');
for (var i = 0; i < list.length; i++) {
if (list[i] === (user + " " + pass + " ")) {
list[i] = user + " " + pass + " " + curBal;
appendItem(curbal, curBal);
console.log(curbal);
console.log(list[i]);
} else {
for (var a = 0; a < balList.length; a++) {
if (list[i] === (user + " " + pass + " " + balList[a])) {
balList[a] = curbal;
list[i] = user + " " + pass + " " + curBal;
}
}
}
}
console.log(totalAccts);
}
As suggested in some of the comments I would change your for loops to start with a zero index:
for (var i = 0; i < list.length; i++)
and
for (var a = 0; a < balList.length; a++)
When I click on my button's at top of textarea it opens either a hyperlink modal or a image insert modal shown in codepen example below.
I can create and insert links and images fine.
How ever when I create the links or image and click save on modal the preview does not show straight away I have to press a key in textarea to see new changes in preview.
Question: When I add a new hyperlink or image from my bootstrap modal
and click save how can I make sure the changes show up in preview
straight away. Using showdown.js
CODEPEN EXAMPLE
Script
$("#message").on('keyup paste copy change', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({parseImgDimensions: true}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end,len) + add_link;
});
function findAvailableNumber(textarea){
var number = 1;
var a = textarea.value;
if(a.indexOf('[1]') > -1){
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste copy change', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({parseImgDimensions: true}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
Just trigger the keyup event at the end of the $("#save-link").on('click', function(e) {});
I assume as jQuery setting value doesn't trigger any of the related events set on $("#message")
$("#message").trigger('keyup');
Just tested on the codepen and works fine,
$("#save-link").on('click', function(e) {
//All your code
// ....
$("#message").trigger('keyup');
});
I hope this helps !!
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>');