how to display the previous user input along with the new input - javascript
I am new to Html and I am trying to create a script to display user input back to the user.whenever i am entering a new input,the new user input over rides the previous input. but i need to display all the user inputs? how to do it using Javascript.
my code
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
display4letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
var fourletter =[];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z,
if (!titles[i].match(/^[a-zA-Z]/)) {
throw error("Please use only alphabet letters");
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else if(titles[i].length == 3){
threeletter.push(titles[i]);
}
else if(titles[i].length == 4){
fourletter.push(titles[i]);
}
}
display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
Try declaring these variables -
var twoletter = [];
var threeletter = [];
var fourletter =[];
before the clearAndShow () function, ie,
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];
function clearAndShow () {
Related
Attempting to retrieve a <select>'s .value with jQuery
So I have this HTML Code/Javascript, var spellNumber = 0; function createSpell() { var spellOption = document.createElement("option"); var spellOption2 = document.createElement("option"); var spellSelect = document.createElement("select"); var spellLabel = document.createElement("label"); var spellEnvelope = document.createElement("p"); spellOption.innerHTML = 'Vanish'; spellOption.setAttribute('value', 'vanish'); spellOption2.innerHTML = 'Teleport'; spellOption2.setAttribute('value', 'teleport'); spellSelect.setAttribute('id', 'spell'); spellSelect.setAttribute('name', 'spell'); spellLabel.setAttribute('for', 'spell'); spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = '; spellEnvelope.appendChild(spellLabel); spellEnvelope.appendChild(spellSelect); spellSelect.appendChild(spellOption); spellSelect.appendChild(spellOption2); document.getElementById("spells").appendChild(spellEnvelope); spellNumber += 1; } createSpell() function generateYaml() { var spellCheck = 1; for (allSpells = 0; allSpells < spellNumber; allSpells++) { var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val(); console.log(multipleSpell); spellCheck++ } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="spells"></div> <button onClick="createSpell()">Add A Spell</button> <button id="button" onClick="generateYaml()">Make the Magic Happen</button> And am trying to retrieve the .value of the <select id="spell"> options. However, the console returns an undefined, instead of vanish or teleport. Can anyone point me in the right direction for this?
Well: Id should be unique so I added spellSelect.setAttribute('id', 'spell' + spellNumber); ( + other rows) Also multipleSpell = $("#spell" + spellCheck).val(); And console.log(multipleSpell); is called only once at the begining -> you should change it to function too ` var spellNumber = 0; function createSpell() { var spellOption = document.createElement("option"); var spellOption2 = document.createElement("option"); var spellSelect = document.createElement("select"); var spellLabel = document.createElement("label"); var spellEnvelope = document.createElement("p"); spellOption.innerHTML = 'Vanish'; spellOption.setAttribute('value', 'vanish'); spellOption2.innerHTML = 'Teleport'; spellOption2.setAttribute('value', 'teleport'); spellSelect.setAttribute('id', 'spell' + spellNumber); spellSelect.setAttribute('name', 'spell' + spellNumber); spellLabel.setAttribute('for', 'spell' + spellNumber); spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = '; spellEnvelope.appendChild(spellLabel); spellEnvelope.appendChild(spellSelect); spellSelect.appendChild(spellOption); spellSelect.appendChild(spellOption2); document.getElementById("spells").appendChild(spellEnvelope); spellNumber += 1; } createSpell() function generateYaml() { var spellCheck = 0; for (allSpells = 0; allSpells < spellNumber; allSpells++) { var multipleSpell = $("#spell" + spellCheck).val(); console.log(multipleSpell); spellCheck++ } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="spells"></div> <button onClick="createSpell()">Add A Spell</button> <button id="button" onClick="generateYaml()">Make the Magic Happen</button>
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val(); More info here. Edited: Well, i see you are trying to get all select values. Why not try this? function generateYaml() { var spellCheck = 1; var selects = $("select").each(function (index, element) { var value = $(element).val() console.log("The value at index %d is %s", index, value); spellCheck++ }); } This way you iterate over all the selects, and get their values inside the loop. Try it here (open the developer console):https://darkcyanpointlessbooleanvalue--parzibyte.repl.co/
Refresh error loading local storage data
Sorry for being such a noob. I'm a student and I can't figure out what is wrong with my script. My code is a budget app where you enter values and it stores the info into local storage. It works when you calculate the expected and actual expenses, but when I refresh the page it adds a new row and with "undefined values". Any ideas? <html> <body onload="load()"> <div id="budget-list"> <ul> <li>Expense Name</li> <li>Expected Amount</li> <li>Actual Amount</li> </ul> <div id="rowContent"></div> <div id="output"> <input type="text" placeholder="Totals"> <input type="text" id="output-expected"> <input type="text" id="output-actual"> </div> <button onclick="addRow()">Add New Row</button> <input type="button" value="Save" onclick="save()" /> <input type="button" value="Add Expected" onclick="addExpectedTotals()" /> <input type="button" value="Add Actual" onclick="addActualTotals()" /> </div><!-- budget-list --> </body> </html> <script> /* BUDGET APP ******** 1. add a new set of rows ******** 2. enter data into input ******** 3. save data to local storage ******** 4. load data from local storage inside respective input id's ******** 5. calculate the total costs of expected/actual columns */ //a new line of rows function addRow(){ var rowNumber = getCurrentCount(); var html = "<div class='rowClass'><input id='name-"+rowNumber+"' type='text'><input id='expected-"+rowNumber+"' type='text'><input id='actual-"+rowNumber+"' type='text'></div>"; var currentHtml = document.getElementById('rowContent').innerHTML; document.getElementById('rowContent').innerHTML = currentHtml + html; } // count the number of divs under rowContent function getCurrentCount(){ var parent = document.getElementById('rowContent'); return parent.getElementsByTagName('div').length; } // add the expected column totals function addExpectedTotals(){ var rowNumber = getCurrentCount(); var all = new Array(); // loop for expected for(i = 0; i < rowNumber; i++){ var expectedCol = document.getElementById("expected-" + [i]).value; var theArray = all[i] = expectedCol; var total = (eval(all.join(' + '))); var stringTotal = JSON.stringify(total); localStorage.setItem("ExpectedTotal", stringTotal); localStorage.getItem(localStorage.key(stringTotal)); var parseTotal = JSON.parse(stringTotal); var ouput = document.getElementById('output-expected').value = parseTotal; } } // add the actual column totals function addActualTotals(){ var rowNumber = getCurrentCount(); var actualArray = new Array(); // loop for actuals for(i = 0; i < rowNumber; i++){ var actualCol = document.getElementById("actual-" + [i]).value; var createArray = actualArray[i] = actualCol; var addActual = (eval(actualArray.join(' + '))); var stringActualTotal = JSON.stringify(addActual); localStorage.setItem("ActualTotal", stringActualTotal); localStorage.getItem(localStorage.key(stringActualTotal)); var parseActualTotal = JSON.parse(stringActualTotal); var actualOutput = document.getElementById('output-actual').value = parseActualTotal; } } // save the data function save(){ var rowNumber = getCurrentCount(); // get the dynamic id for #name for(var i = 0; i < rowNumber; i++){ var keyName = i; var inputName = document.getElementById("name-" + [i]).value; var inputExpected = document.getElementById("expected-" + [i]).value; var inputActual = document.getElementById("actual-" + [i]).value; var allIds = [inputName, inputExpected, inputActual]; var key_json = JSON.stringify(allIds); localStorage.setItem("Item-" + i, key_json); } } //load the data function load(){ // add a new row for the data that is loaded for(i = 0; i < localStorage.length; i++){ addRow(); } // loop through the input fields and parse the data for(i = 0; i < localStorage.length; i++){ var row = localStorage.getItem(localStorage.key(i)); var parsed = JSON.parse(row); document.getElementById("name-" + i).value = parsed[0]; document.getElementById("expected-" + i).value = parsed[1]; document.getElementById("actual-" + i).value = parsed[2]; } } // initialize the app with a set of rows document.addEventListener("DOMContentLoaded", function(event) { addRow(); });
How to dynamically create buttons based on random conditions
I have created a button using JavaScript, and I have a list that is supposed to get a random number when I "roll the dice" I need to list of numbers to say "You rolled a 1" for example. How do I do that? And also I only need it to show the last 10 numbers. var rollNumber = 0; var values = []; function dieRolled() { rollNumber += 1; var numRolled = Math.ceil(Math.random() * 6); values.push(numRolled); document.getElementById("results").innerHTML = ""; for (var x = values.length-1 ; x>=0; x--) { var newRoll = document.createElement("li"); newRoll.innerHTML = values [x] +"You rolled a"; document.getElementById("results").appendChild(newRoll); if (x == 11)break; } }
How about this? var output = document.getElementById("Output"); var values = []; function roll() { values.push(Math.ceil(Math.random() * 6)); // If the history is too big, drop the oldest... if (values.length > 10) { values.shift(); } // Rewriting the history log var text = ""; for (var i in values) { text += "You rolled a " + values[i] + "\n"; } output.innerHTML = text; } // Rolling multiple times setInterval(function(){ roll(); }, 1000); <pre id="Output"></pre>
Try this: var list = document.getElementById('demo'); var count = 0; function changeText2() { count++; if(count <= 10) { var numRolled = Math.ceil(Math.random() * 6); var entry = document.createElement('li'); entry.appendChild(document.createTextNode("You rolled:"+numRolled)); list.appendChild(entry); } } <input type='button' onclick='changeText2()' value='Submit' /> <p>Dices you rolled</p> <ol id="demo"></ol>
How to get rid of all double commas
No this isn't a duplicate because all of the answers are different in other posts. Does anyone know how to get replace something specific in a string? for example I'm trying to get rid of ALL commas that area together. Keep single commas but get rid of two only For example: w,h,o,,w,h,a,t,w,h,e,n,w,h,e,r,e,,t,h,e,n,,c,a,n,,b,u,t,, I want to get rid of all instances where the double commas appear. Something kind of like: var example = text.replace(/,,/g,' '); /*Space where ' ' is*/ If you understand what I mean. The next step is: var text.replace(/,/g,''); Thank you! Code: <html> <head> <script> function decrypt() { var input = document.getElementById("input").value; var x = input.split(","); var txtDisp=""; for(var i = 0; i < x.length; i++) { if(x[i].type = "text") { crack = 94-(x[i]-32)+32; toTxt = String.fromCharCode(this, crack); txtDisp = txtDisp+","+toTxt; prep = txtDisp.replace(/,,/g,""); } document.getElementById("prompt").innerHTML=prep; } } </script> </head> <body> <textarea rows='4' cols='100' style='resize:none;' id='input'></textarea> <br> <input type='button' value='execute' onclick='decrypt()' /> <p id='prompt'> </p> </body> </html> P.s. this code is already posted somewhere else where I asked a question.
Why don't you do: var text = "61,59,44,47,43,43, ,39,54,37, ,37,47,41,44, ,59,61,48, ,53,48,42,47, ,42,54,57,53,44, ,47,56,42,57,48, ,47,56,56, ,43,61,53,58, ,47,41,44, ,42,39,61,43, ,43,53,48,59,57, ,42,54,57,44,57, ,61,48,58, ,39,47,41,50,58"; example = text.split(",,").join("").split(", ,").join(""); the result is: "w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t" I myself also tried to do it like: example = text.replace(/,,/g,'').replace(/, ,/g,''); the result was: "w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t" I changed your code like this: function decrypt() { var val = document.getElementById("input").value; var x = val.split(","); var txtDisp = ""; for (var i = 0; i < x.length; i++) { if (!isNaN(parseInt(x[i]))) { var num = parseInt(x[i]); crack = 94 - (num - 32) + 32; toTxt = String.fromCharCode(this, crack); txtDisp = txtDisp + "," + toTxt; prep = txtDisp.replace(/,,/g, "").replace(/, ,/g, ""); } document.getElementById("prompt").innerHTML = prep; } } and it works. check this DEMO out.
Try this: function decrypt() { var input = document.getElementById("input").value; var x = input.split(","); var txtDisp = ""; for (var i = 0; i < x.length; i++) { if (x[i] !== ' ') { crack = 94 - (x[i] - 32) + 32; toTxt = String.fromCharCode(this, crack); txtDisp += "," + toTxt; } else { txtDisp += " "; } } document.getElementById("prompt").innerHTML = txtDisp.replace(/,/g, ""); }
change numbers from dynamic elements
I have this code that sends the values a user have typed in... the information and numbers are sent as an array and pushed into another array, I then display the text in a dynamically created list element and number in a span element... var button = $('#add'); button.click(function() { var filmnamn = $('#name'); var filmnamnet = filmnamn.val(); var betyg = $('#star'); var betyget = betyg.val(); betyget = Number(betyget); if(filmnamnet == 0) { $('#name').css('background-color', 'red'); } if(betyget == 0) { $('#star').css('background-color', 'red'); } if(betyget == 0 || filmnamnet == 0) { alert("Vänligen fyll i fälten korrekt"); } else { var array = new Array(); array.unshift(betyget); array.unshift(filmnamnet); film_array.unshift(array); betyg_array.unshift(array); updateFilmList(); } }); var film_list = $("#filmlista"); var film_array = new Array(); function updateFilmList() { document.getElementById("name").value = ''; document.getElementById("star").value = 0; var filmen = film_array[0][0]; var grade = film_array[0][1]; var element = '<li class="lista">' + filmen + '<span class="betyg">'+ grade +'</span></li>'; film_list.append(element); changeNumber(); } And at last I have the function that i want to change the number in the span element to the amount of stars that the number shows... this works fine but only for the first created list and span element, when I try to add more listelements the number wont show up as stars, can someone tell me why this happens and point me in the direction to fix the problem? function changeNumber(){ var elements= document.getElementsByClassName("betyg"); for (var i=0; i<elements.length; i++) { var element = elements[i]; var length = parseInt(element.innerHTML); var x=Array(length+1).join("*"); element.innerHTML=x; } }