Replace previously generated content in Javascript based on user input - javascript

I have a button on that perfroms the collatz conjecture with the push of a button, and takes in the user's input. It then prints out the steps as a list into a p tag. I wanted to know how I would override the previously created steps, as I have noticed calling the method again adds to the end of the previous list.
The main reason I'm using a list is for readability, so I don't want to get rid of it unless there's a better way of doing this.
//collatz function
function collatz (){
var step = 0;
var inputCollatz = prompt("What number do you want to add?")
if (inputCollatz <= 1){
document.getElementById("collatz").innerHTML = "No steps required, already less than or equal to 1.";
}
else if(isNaN(inputCollatz)){
document.getElementById("collatz").innerHTML = "Please add a number.";
}
else if (inputCollatz.toString().indexOf('.') != -1){
document.getElementById("collatz").innerHTML = "Whole numbers please!";
}
else{
while(inputCollatz > 1){
//needed help w/ ternary operators, still need practice with it
inputCollatz = inputCollatz % 2 ? 3 * inputCollatz + 1 : inputCollatz / 2;
step++;
var item = document.createElement("li");
var text = document.createTextNode(inputCollatz);
item.appendChild(text);
var list = document.getElementById("collatz");
list.appendChild(item);
}
document.getElementById("steps").innerHTML = "Number of steps: " + step.toString();
}
}
This is the button in html.
<button onclick="collatz()">Find the number of steps.</button><br/>
<br/>
<div id="collatz"></div>
<br/>
<div id="steps"></div>

I was suggested to clear out the collatz div before each loop, which worked.
...
else {
document.getElementById("collatz").innerHTML = '';
while(inputCollatz > 1) {
....

Related

Change h1 using javascript switch statement based on input

I need to know how to get the h1 sun emoji to change when user input less than or equal to 0.
I feel like I have the logic but just need to code.
Once the user inputs a temperature less than 0 the h1 needs to change to a certain emoji or content.
Can I get some advice please. I am struggling here. this is my code:
function question() {
let city = prompt("what city do you live in?");
let temp = prompt("What temperature is it?");
let h1 = document.queryselector("h1");
h1.innerHtml = "Currently" + temp + "degrees" + " in " + city;
}
function change() {
switch (true) {
case (temp <= 0):
document.getElementById("h1").innerHtml = "Currently" + temp + "degrees" + "in " + city;
}
}
<h1>
sun emoji
</h1>
<h1 class="temperature">
Currently 21 degrees in Tokyo
</h1>
<h2>
13 degrees / <strong>23 degrees</strong>
</h2>
The h1 has to change to a different emoji based on the users response of less than or equal to 0.
Along with the emoji I need to input of the user city to change along with it.I just need the h1 section to change.Should I use a switch or if else statement?
Firstly, you have multiple h1 elements - queryselector only returns the first one, so in this case you would be replacing the emoji, not the text.
It would be prudent to give the various elements that you intend to edit id fields.
<h1 id="emoji-el">
sun emoji
</h1>
<h1 id="temp-details" class="temperature">
Currently 21 degrees in Tokyo
</h1>
Now you can use queryselector to select the correct elements.
Secondly, I'd like to say that it is good practice to have every function have a single responsibility - for example, one function get a correct emoji, while another puts things into elements.
Given this, I would use an if list because of the way your condition is structured:
function getEmoji(temp) {
if (temp < 0) return ❄️;
if (temp < 13) return ☁;
return ☀️;
}
You can likely use emojis directly for HTML text values, and if you only use upper limits like I did you don't need elses. IMO this is the nicest way.
You final function would look something like this:
function questionUser() {
const city = prompt("What city do you live in?");
const temp = prompt("What temperature is it?");
updatePage(temp, city);
}
function updatePage(temp, city) {
const emojiElement = document.queryselector("#emoji-el");
const tempElement = document.queryselector("#temp-details");
const emoji = getEmoji(Number(temp));
emojiElement.innerHtml = emoji;
tempElement.innerHtml = `Currently ${temp} degrees in ${city}.`;
}
This way you would be able to re-use the update logic elsewhere, and also it is clear what every function does.
Hope this helps.
Can achieve the same result with switch or if statement.
You just have to trigger the function on onChange or onBlur.
It's advisable to use classNames or id's for your html element, which makes retrieving specific elements easier.
Switch is suitable if your conditions have a fixed value. In this case a a ternary (conditional operator) would be an idea.
Here's an exemplary snippet demoing ternary or switch to determine the 'emoji' to display, based on the given temperature. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function handle(evt) {
// act only if button#showTemperatures is clicked
if (evt.target.id === `showTemperatures`) {
return question();
}
}
function emo(temp) {
const emojiTxt = temp < 15 ? `*Brr**` :
temp < 25 ? `*nice*` :
temp < 30 ? `*it's getting hot here*` : `*tropical!*`;
document.querySelector(`.emoji`).textContent = emojiTxt;
}
/* using switch is possible, but you need something extra */
function emoSwitch(temp) {
const lt = n => temp < n;
let emojiTxt = ``;
switch (true) {
case lt(10):
emojiTxt = `*Brr*`;
break;
case lt(25):
emojiTxt = `*nice*`;
break;
case lt(30):
emojiTxt = `*it's getting hot here*`;
break;
default:
emojiTxt = `*tropical!*`;
}
document.querySelector(`.emoji`).textContent = emojiTxt;
}
function question() {
// id's make your coding life simple
const city = document.querySelector(`#city`).value;
const temp = document.querySelector(`#temp`).value;
// one of the values is not filled, alert
if (!city.trim() || temp < 0) {
return alert(`please fill out both fields`);
}
// fill in h1.temperature
document.querySelector(`.temperature`).textContent =
`Currently ${temp} degrees in ${city}`;
// fill in the emoji
return document.querySelector(`#switch`).checked ?
emoSwitch(temp) : emo(temp);
}
<!-- changed for demo -->
<p>
<b class="emoji"></b>
<b class="temperature">Currently 21 degrees in Tokyo</b>
</p>
<hr>
<p><input type="text" id="city"> What city do you live in?</p>
<p><input type="number" id="temp" min="0" max="55"> What temperature is it up there?</p>
<p>
<button id="showTemperatures">Fill in</button>
<input type="checkbox" id="switch">Use switch
</p>

How to setup a list with removable items that stores itself in localStorage in javaScript

I have been working on a little project and I need some values to be stored in an array, that would be displayed at all times, even if the page reloads, and that could be removed by pressing a button.
The idea that I had is to store the array in localStorage, and every time the page loads, they get downloaded into the javascript array.
That seems to work flawlessly, but my problems come when I am trying to remove them by pressing a button. I know where the problem in my code is, I just don't know how to do it so that it works.
The problem is that, after I delete an item with a low index, it messes with my ability to later delete items with higher index.
Here's the code:
var input = document.getElementById("text");
var displayed = input.value;
var a = [];
function check() {
if (localStorage.session == null) {
a.push(JSON.parse(localStorage.getItem('session')));
a.splice(0, 1);
localStorage.setItem('session', JSON.stringify(a));
}
}
function SaveDataToLocalStorage() {
a = JSON.parse(localStorage.getItem('session'));
if (input.value !== "input") {
a.push("<p>" + input.value + " </p><button onclick='Delete(" + (a.length - 1) + ")'>Delete</button><br />");
} else {
displayed = "";
}
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
function Delete(deleted) {
var index = deleted;
a.splice(deleted, 1);
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
check();
SaveDataToLocalStorage();
<input type="text" name="input" value="input" id="text">
<button onclick="SaveDataToLocalStorage()">Click</button>
<div id="Demo">
If anyone could help, It would be Amazing!
I didn't test the code but I think this can help you out!
var input = document.getElementById("text");
var displayed = input.value;
var a = [];
function check() {
if (localStorage.session == null) {
a.push(JSON.parse(localStorage.getItem('session')));
a.splice(0, 1);
localStorage.setItem('session', JSON.stringify(a));
}
}
function SaveDataToLocalStorage() {
a = JSON.parse(localStorage.getItem('session'));
if (input.value !== "input") {
a.push({
index: a.length,
data: "<p>" + input.value + " </p><button onclick='Delete(" + a.length + ")'>Delete</button><br />"
});
} else {
displayed = "";
}
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
function Delete (deleted) {
a = a.filter(function (e) { return e.index !== deleted })
localStorage.setItem('session', JSON.stringify(a));
document.getElementById("Demo").innerHTML = a.join("");
}
check();
SaveDataToLocalStorage();
<input type="text" name="input" value="input" id="text">
<button onclick="SaveDataToLocalStorage()">Click</button>
<div id="Demo">
Your problem is with this
a.push("<p>" + input.value + " </p><button onclick='Delete(" + (a.length - 1) + ")'>Delete</button><br />");
You're hardcoding the index to delete in the Delete button, but the index can change if you delete an item from earlier in the array.
You could consider re-rendering everything, including the buttons, every time your array changes.
Another alternative is that every item in your array can have an ID, and that would not change when an earlier one is deleted. Then you can make your 'delete' function remove an element from the array based on its ID.
One more solution: make the button click function check it's own index upon click (eg check if it's the 2nd delete button or the 9th delete button), and delete from the array the index that it gets from that check. That way you can keep most of your code the same, but the index isn't hardcoded into the button, it's live-checked every time.

How to set a check if coupon code used one time then do not allow to use it second time in one transection

This is my code
html input field
<input type="text" size = "3" name="couponadd" id="couponadd"
oninput="myFunction()" class="field" placeholder="Enter Coupon Code" />
Script Code
<script>
var lastval;
function myFunction() {
getting CouponDC,TicketypDC and CouponPrcDC from database
var CouponDC = $('#dbcoupan').val();
var TicketypDC = $('#dbtckettype').val();
var CouponPrcDC = $('#dbprice').val();
var total_price = $('#total_price').val();
Get getcoupon from input
var getcoupon = $("#couponadd").val(),
txt='Invaild Coupon';
check if user enter same coupon
if(getcoupon == lastval )
{
alert('You Cant Enter Same Code Again');
}
if coupon code match with database coupon
else if (getcoupon == CouponDC ) {
$amount=CouponPrcDC;
total_price = total_price * ((100-$amount) / 100);
minus some ammout from total if match
total_price = Math.round(total_price);
document.getElementById('Voucher_value').value = total_price;
}
if coupo don't match with database coupon
else if(getcoupon != CouponDC && getcoupon.length ==5 )
{
alert('WRONG COUPON CODE');
}
**store last value enter in input**
lastval = getcoupon;
$('#total_price').val(total_price);
}
</script>
You can store it in an array and check if it exists before moving ahead.
Pseudo code below:
var couponArr = [];
var getcoupon = $("#couponadd").val();
if($.inArray(getcoupon, couponArr) !== -1) {
alert('Coupon already used, can\'t use again.');
} else {
couponArr.push(getcoupon);
// your code here..
}
inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
Add a global tag variable and set default to false,use a if condition wrap the code need to run,then in the run code set it to true.
such as:
// in outer space
var hasCodeRun = false;
// in some function
if (!hasCodeRun) {
// run code here
hasCodeRun = true;
}

Keep form data with back button

there are many questions similar to this but none of them seem to help with my situation.
I am developing a three step process using Javascript and html
I have 2 forms in the first two steps.each with a next/prev button
I need to be able to go back from step two back to step 1 and still have step ones form data in the fields. I am rather new to javascript any help would be appreciated. I am unsure how to save the form data and then insert it when the user goes back from step 2
EDIT:
I have decided to use JS to hide/show forms, please can someone tell me why my variable never gets to currentStep == 3; this causes issues when going back as it goes back to step one becasue the currentStep value is stuck at 2
var currentStep = 1;
function nextStep() {
if (currentStep ===1){
$("#petmain1").hide();
$("#petmain2").show();
$("#addproduct").show();
$("#firstimage").hide();
$("#secondimage").show();
currentStep = 2;
console.log("Current step is " + currentStep);
}else if(currentStep ===2){
$("#petmain2").hide();
$("#addproduct").hide();
$("#secondimage").hide();
$("#petmain3").show();
$("#thirdimage").show();
$("#firstimage").hide();
currentStep === 3;
console.log("Current step is " + currentStep);
}
}
function prevStep() {
if (currentStep ===2){
$("#petmain1").show();
$("#petmain2").hide();
$("#addproduct").hide();
$("#firstimage").show();
$("#secondimage").hide();
currentStep = 1;
console.log("Current step is " + currentStep);
}else if(currentStep === 3){
$("#petmain3").hide();
$("#thirdimage").hide();
$("#secondimage").show();
$("#petmain2").show();
$("#addproduct").show();
currentStep === 2;
console.log("Current step is " + currentStep);
}
}
You can use localStorage
On navigating from first step to second step you can store the value
if(typeof(Storage) !== "undefined") {
localStorage.setItem("someKey", $("#somField").val());
} else {
//
}
Again on navigating from second to first step check the local storage for the value and assign it to the fields in first form
$("#somField").val(localStorage.getItem("someKey"))
You may use sessionStorage.
HTML
<form>
Username : <input type='text' id='name'> <br />
Password : <input type='password' id='password'> <br />
<input type='button' onclick='storedata()' value='submit'>
</form>
<p id='res'></p>
JS
window.onload = function() {
if (sessionStorage.name && sessionStorage.password) {
document.getElementById("name").value = sessionStorage.name;
document.getElementById("password").value = sessionStorage.password;
}
};
function storedata() {
if(typeof(Storage) !== "undefined") {
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
sessionStorage.name = name;
sessionStorage.password = password;
document.getElementById("res").innerHTML = "Your datas restored";
} else {
document.getElementById("res").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Working Demo : https://jsfiddle.net/d83ohf6L/

Text Box Search / Javascript Function Arrays **not corresponding**

I want the user to "Search" some "Authors" and if they select the one in the database they are sent to a corresponding HTML. Otherwise "No Author Found" displays...
For some reason I cannot wrangle it properly - pls help!
//Search by Author
function searchAuth() {
var search_string = document.getElementById('search_string').value;
var arrayelement = ["John","Stan","Henry","Paul","Samuel"];
for (i=0;i<arrayelement.length;i++) {
if (input == arrayelement.John) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
} else if (input == arrayelement.Stan) {
var itemLink = document.getElementById('demo').innerHTML =
"<a href='https://www.google.ca/?gws_rd=ssl'>Your link</a>";
}else {
var itemLink = document.getElementById('demo').innerHTML =
"Author not found."
}
}
<!--Author-->
<h3>Search By Author</h3>
<form name="searchTest" onsubmit="return(searchAuth());" action="#">
<input type="text" id="search_string" />
<input type="submit"/>
<p id="demo"></p>
Perhaps you are trying to do things like these..
P.S this is just a demo, for you to start :)
EDIT: added few explanation on some stuffs you might get confuse with. :)
//events once textbox gets out focus
//the events varies on which or where do you want to add the event. it can be on click of a search button or submit button just like in your example.
document.getElementById('search-text-box-id').addEventListener("focusout", function() {
//searchString gets the textbox value.
var searchString = document.getElementById('search-text-box-id').value;
var searchList = ["John","Stan","Henry","Paul","Samuel"];
//Loop searchList
for (i=0; i < searchList.length; i++) {
//i which usually means the index or the key of the array's object(s).
var searchItem = "";
//searchList[i] loops its object by getting the index resulting to John, Stan and so on and so forth.
if (searchString == searchList[i]) {
searchItem = searchList[i];
document.getElementById('search-result-container').innerHTML = searchItem + " link";
//stop looping as the loop found a match.
return;
}
else {
searchItem = "Author not found.";
document.getElementById('search-result-container').innerHTML = searchItem;
}
}
});
<label for="search-text-box"></label>
<input type="text" id="search-text-box-id" name="search-text-box" />
<p id="search-result-container"></p>

Categories