How to remove elements from array - javascript

Thanks for viewing. I have a program that can create a list of user inputs. The program can add people & remove people (starting from the top). This program also limits inputs to 7.
When the limit is reached, the oldest input in the array gets erased, and then the new input is going to appear. Basically:
a b c d e f g
(a is the oldest, and the g is the newest)
Becomes:
b c d e f g h
However, even if the program can already add elements in the array, what I can't understand is that although my program has the pop()function to remove people, I still can't remove anyone from my list. Furthermore, the input limitations is not followed.
Is there a missing part in my code that does the problem? Thanks.
var people = [7];
function myFunction() {
var x = document.getElementById("list");
people.push(document.getElementById("input").value);
x.innerHTML = people.join('<br/>');
}
function myFunctions() {
var x = document.getElementById("list");
people.pop();
console.log(people);
}
<!DOCTYPE html>
<html>
<body>
<form>
<input id="input" type=text>
<input type=button onclick="myFunction()" value="Add" />
<input type=button onclick="myFunctions()" value="Remove" />
</form>
<div id="list">
</div>
</body>

Please, check if it was you want?
It seems you expect that vanilla javascript variables be reactive as in vue js or react js but they don't.
<!DOCTYPE html>
<html>
<style>
</style>
<script>
var people = [7];
function myFunction()
{
if(people.length === 7) // you should check the array size
return console.log("it can't add more people!");
var x = document.getElementById("list");
people.push(document.getElementById("input").value);
x.innerHTML = people.join('<br/>');
}
function myFunctions()
{
var x = document.getElementById("list");
people.pop();
x.innerHTML = people.join('<br/>'); // you should update the list
console.log(people);
}
</script>
<body>
<form>
<input id="input" type=text>
<input type=button onclick="myFunction()" value="Add"/>
<input type=button onclick="myFunctions()" value="Remove"/>
</form>
<div id="list">
</div>
</body>

I'm not sure if you remember the definition of index, but an array list of 7 is supposed to be [6], as the corresponding index to every variable in the list starts with 0 instead of 1.
Try to update your list before you go straight to console.log!

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

Why does my delete all button need to be double clicked to work?

So, I was adding a delete all button and it works, the only problem is that it needs to be double clicked just to make it work.
may I ask what's wrong? thank you :)
I added the codes that were used to create the button here:
<body>
<!--for everything in the navigation part including the add favorite bar-->
<div class="topnav">
<div class="addFave">
<!--the text bar-->
<input type="text" name="enter" class="enter" value="" id="added" placeholder= "Add Favorites"/>
<!--the enter button-->
<input type="button" value="Enter" id = "addIt" OnClick="adding()" />
<!--for the script of the add favorite bar to add its functions-->
<script type="text/javascript">
var faves = [];
var y = document.getElementById("added");
function adding() {
faves.push(y.value);
document.getElementById("faveLists").innerHTML = faves;
}
var input = document.getElementById("added");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("addIt").click();
}
});
</script>
</div>
</div>
<br />
<div class="buttons">
<button onclick="eradicateFaves()">Remove All Favorite</button>
<script>
-coding to remove all the favorites on the list-->
function eradicateFaves(){
document.getElementById("faveLists").innerHTML = faves;
while(faves.length > 0){
faves.shift();
}
}
</script>
</div>
<p id = "faveLists"></p>
while(faves.length > 0){
faves.shift();
}
Why not just faves = [] to empty it? And shouldn't you empty the list before assigning it? That's why you need two clicks; first time re-assigns current list then empties it, and second time assigns the empty list then does nothing more as it is already empty. So, try this:
function eradicateFaves(){
faves = [];
document.getElementById("faveLists").innerHTML = faves;
}
When you say "delete all" I assume you mean reset the faves array back to []. Well why not just do this:
function eradicateFaves() {
faces = [];
document.getElementById("faveLists").innerHTML = faves;
}
The reason it wasn't working earlier was because Array.prototype.shift() only removes the first element of the array. According to the MDN docs:
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How to make an html form start a function

I'm wondering if there is an easy way to make a form button with text input start a form that will check if the answer's correct and then proceed to tell you. Here's what I have, can you tell me what I need?
<!doctype html>
<body>
<center>
<form name="Input" action="Answer" method="get">
<input type="text" name="Input">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
document.write(A + "+" + B)
function Answer()
{
alert("correct!!");
}
</script>
</body>
</html>
function calculateAnswer()
{
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
if(Input.value == C)
{
document.body.innerHTML += (A + "+" + B);
// Or another thing to do if the answer's correct
}
}
Also, attach an event listener to the submit button to make it run the function:
referenceToTheSubmitButton.addEventListener("click", calculateAnswer);
Indent as needed.
Enjoy! :D
I know you aren't using jQuery, but are you looking for something of this nature?
It can easily be changed to plain javascript. I just wanted to use bootstrap for the easy visual effect of the alerts.
The html would be something along these lines (with jQuery and bootstrap):
<div class="alert alert-danger" id="correct">Your answer is currently
<span id="type"> INCORRECT </span>
</div>
<form>
<input name="answer" id="answer">
</form>
<p>Hint: the answer is "correct"</p>
and the script would work like this:
$("#answer").keyup(function(){
if($(this).val() === "correct"){
$("#correct").removeClass("alert-danger")
.addClass("alert-success");
$("#type").text("CORRECT!")
}
else{
$("#correct").removeClass("alert-success")
.addClass("alert-danger");
$("#type").text("INCORRECT!")
}
}).keyup();
This is just a basic implementation of an input that checks for an answer. In this case, typing "correct" makes the alert green.

Get a list of outputs with a while loop using javaScript

i m trying to get a list of outputs which doesn't divide evenly by number which are smaller than the input value.For example if the input value is 10,the list should be 10,9,8,7,6,4,3,1. below is my code and doesn't give me any output nor any error message.I m new to javascript and i need to know what i m doing wrong.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>An example of using "for" and "while" in PHP</title>
<script type="text/javascript">
function displayResult()
{
if(text_form.numberfield.value){
var number=document.getElementsByName("numberfield").value;
var div=document.getElementsByName("numberfield").value;
while (div>0)
{
if(number%div==0 && div!=number && div!=1)
{
div--;
continue;
}
if (div == 0)
{
break;
}
document.write(div--);
document.write(",");
}
}
else
{
document.write("Enter a number");
}
}
</script>
</head>
<body>
<H1>An example of using "for" and "while" in PHP</H1>
<form name="text_form">
Please input a number: <input type="text" name="numberfield"> </label>
<input type="submit" value="Submit" onclick="displayResult()" />
</form>
<p> Result is shown as below.</p>
</body>
</HTML>
getElementsByName returns an array, not an element.
Try:
var number=document.getElementsByName("numberfield")[0].value;
var div=document.getElementsByName("numberfield")[0].value;
Notice the [0]. You also have to modify a bit to make it work.
DEMO
the getElementsByName returns a list of elements having the specified name not a single element. You can access each element using loop:
var elems=document.getElementsByName("name")
for(var i=0;i<elems.length;i++){
var elem=elems[i]
//access each element using iterator
}
Also the getElementsByTagName returns a list of elements having the specified tag name.

How to pass input variable from HTML Form

I'm trying to create a code which will take ask the user how many items of X, Y, etc and use Javascript to calculate the total owed and also to print a summary (receipt) of all items purchased. Sorry for noob question, trying to learn code without any formal training. Thanks for all of the help!
<html>
<head>
<title>Cost Calculator</title>
<script language="javascript" type="text/javascript">
function packageTotal(){
//Enter in prices here
var applePrice = 1;
var bookPrice = 2;
x = Number(document.calculator.books.value);
y = Number(document.calculator.apples.value);
var b = applePrice*x + bookPrice*y;
var p = applePrice*x + bookPrice*y + .5;
if (document.getElementById('noBag').checked) {
//Basic package is checked
document.calculator.total.value = b;
} else if (document.getElementById('yesBag').checked) {
//Pro package is checked
document.calculator.total.value = p;
}
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
}
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- Here user will enter the number of Books and Apples -->
Enter Number of Books: <input type="text" name="books">
<br />
Enter the Number of Apples: <input type="text" name="apples">
<br />
<br />
<input type="radio" name="item" id="noBag" value="No" /> noBag
<input type="radio" name="item" id="yesBag" value="Yes" checked /> yesBag
<!-- Here result will be displayed. -->
<input type="button" value="Submit" onclick="packageTotal();">
Your Total Price is: <input type="text" name="total">
</form>
</body>
</html>
It's not clear from the question, but if this is the problem:
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
then that would certainly break. document.write only adds to the current document when the document is still loading. If you call it afterwards it will implicitly open a new document to write to, destroying the current page. Generally document.write is a bad thing.
(also there are trivial syntax errors due to missing + concatenation operators)
If you want to write arbitrary text to the page, create a placeholder element:
<div id="message"></div>
and then set its text content:
function setTextContent(element, text) {
element.innerHTML = ''; // remove current content
element.appendChild(document.createTextNode(text));
}
var message = document.getElementById('message');
setTextContent(message, 'You want '+x+' books and '+y+' apples.');
(There is a textContent property on elements which you can also use instead of the function, but it's not supported on IE<9 which use innerText instead. Simply writing the message directly to innerHTML would also work in this case, but it is a bad habit because it leads to HTML-injection security holes when used with user input.)

Categories