store value into an array JS - javascript

I would like to store some values into an array in HTML. The values are from a random number generator in Python as {{player.a1s1}}. This has been taken care of. basically, when on each click on button "mm1a" , the player will see one more button in the form. the number of clicks will be recorded. and I would like to have the random number {{player.a1s1}} shown on the button to be stored in JS as an array. My code could not store the value into array.
HTML
<div class="container1">
<p>
{{ player.text1a }} # this will get the text from a python variable.
</p>
<form id="frm1">
<button class="toAdd">{{player.a1s1}}</button>
<button class="toAdd">{{player.a1s1}}</button>
<button class="toAdd">{{player.a1s1}}</button>
<button class="toAdd">{{player.a1s1}}</button>
<button class="toAdd">{{player.a1s1}}</button>
<button class="toAdd">{{player.a1s1}}</button>
</form>
</div>
<div><button class="mm1a" type="button">{{ player.optiona1 }}</button>
# this will get the innerhtml from another python variable.
</div>
<p>
samplemma1<input id="id_samplemma1" name="samplemma1" value="0"></input>
</p>
in javascript
$('.mm1a').on('click',function(){
$('.toAdd:eq('+count+')').show();
count++;
hello();
getarraya();
});
var clicks = 0; # to count how many clickes the players did
function hello() {
clicks += 1;
document.getElementById("id_clicksmma1").innerHTML = clicks;
document.getElementById("id_clicksmma1").value = clicks;
};
# below part does not work
var myarraya = [];
var c = 0;
function getarraya() {
c += 1;
myarraya.push(document.forms["frm1"].elements[c].innerHTML);
document.getElementById("id_clicksmma1").innerHTML = myarraya;
document.getElementById("id_clicksmma1").value = myarraya;
};

jquery "on" must be inside document.ready and variable myarraya
and c move it to top.

Related

making javascript variables keep their value

I am very new to Javascript and I was wondering if anyone could help me for what seems to be quite a simple question to anyone who knows anything about JS. My problem is that I am trying to change the value of my variables after declaring them but everytime I change their values they are set back to what they used to be when they got declared. If anyone could please explain how I could work my way around this problem it would be greatly appreciated, Here's my code if you want to see it:
//Anything before this doesn't matter for my question.
<td>
<p id="first"></p> <--- this prints the "first" var declared in the script bellow but is always equal to 1 even when the button is pressed
</td>
<th class="col-xs-1 align-middle text-center">
<div class="btn-group">
<a class="btn btn-default btn-sm btn-add-all" onclick="value_up(first);"> <--- this is the button that calls the function when pressed
<i class="fa fa-arrow-up"></i>
</a>
</div>
<script>
var first = 1; <--- this is where I declare my variable
document.getElementById("first").innerHTML = first; <--- Here's where I pass my variable to the <p> tags up above
</script>
</tbody>
</table>
</div>
</div>
</div>
<script>
function value_up(x) { <--- this is the function I am calling when I press the up button
x = x - 1;
console.log(x);
return (x);
}
</script>
You're returning x but never setting first to x. As such, first never changes. Values are passed in by value in javascript and so you need to change the value of first directly instead of just passing it in.
You also need to reupdate the value that your HTML element holds. Please check the following example:
let first = 0
document.getElementById("first-val").innerHTML = first;
let increment_first = () =>{
first += 1
document.getElementById("first-val").innerHTML = first;
}
<p> Value of first: <span id="first-val"></span></p>
<button onclick="increment_first()">Increment!</button>
To be slightly more robust pass the id and then get/set using the passed id
var first = 1;
document.getElementById("first").innerHTML = first;
function value_up(id) {
var x = parseInt(document.getElementById(id).textContent)
x+=1 // or whatever operation you want
document.getElementById(id).innerHTML = x
}
<p id="first"></p>
<input type="button" value="UP" onclick="value_up('first');">

Clilcking on a button is giving a Bad Path error

I'm trying to make a pen which incorporates the javascript exercises I'm learning. Here is the Pen: https://codepen.io/ychalfari/pen/JVYoNW
In this specific case I'm trying to accept an array from an input and run a function which sums the array when you click the button, and the result should show underneath.
When I click the button I either get an Error: "Bad Path /boomboom/index.html"
or nothing happens the page just kind of reloads and it takes me to the top of the page.
The HTML
<form id="sum-arr-form">
<div class="form-wrap" >
<label for="arr-to-sum"> Enter an Array to sum: <input id="arr-to-sum" class ="med-input" type="text" value = "">
<button class="btn1" onclick ="sumOfArray()">submit</div> </form>
<p>Result: <span id="demo"></span></p>
The Javascript
let inputArr = document.getElementById('arr-to-sum').value;
const add = (a,b) => a+b;
const sumOfArray = function() {
let sum = inputArr.reduce(add);
document.getElementById("demo").innerHTML = sum;};
You have some mistakes in your code.(button tag without type will trigger submit)
<button class="btn1" onclick ="sumOfArray()">submit
change this line to
<input type="button "class="btn1" onclick ="sumOfArray()" value="submit">
then get the value of input inside your sumOfArray function. (add the below 2 lines in your sumOfArray function) (waynelpu's answer above)
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);
The value get from input is string, if you want to process it as array you need to convert to correct type in js, try
let inputArrStr = document.getElementById('arr-to-sum').value;
let inputArr = JSON.parse(inputArrStr);

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.

Using Input Number to Update Number of Paragraphs Displayed - HTML Javascript

I'm trying to use a input number type to update how many times a particular amount of content is added to the page. In the example I'm doing it with a p tag but in my main model I'm using it on a larger scale with multiple divs. However, I can't seem to be able to get this to work. If someone can see where I'm going wrong that would be very helpful.
function updatePage() {
var i = document.getElementById("numerInput").value;
document.getElementById("content").innerHTML =
while (i > 1) {
"<p>Content<p/><br>";
i--;
};
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
<p>Content
<p>
<br>
</div>
First, you have quite a few problems that need addressing:
You are setting the .innerHTML to a while loop, which is invalid because a loop doesn't have a return value. And, inside your loop, you just have a string of HTML. It isn't being returned or assigned to anything, so nothing will happen with it.
You've also mis-spelled the id of your input:
document.getElementById("numerInput")
Also, don't use inline HTML event attributes (i.e. onclick) as there are many reasons not to use this 20+ year old antiquated technique that just will not die. Separate all your JavaScript work from your HTML.
Lastly, your HTML is invalid:
"<p>Content<p/><br>"
Should be:
"<p>Content</p>"
Notice that in addition to fixing the syntax for the closing p, the <br> has been removed. Don't use <br> simply to add spacing to a document - do that with CSS. <br> should be used only to insert a line feed into some content because that content should be broken up, but not into new sections.
Now, to solve your overall issue, what you should do is set the .innerHTML to the return value from a function or, more simply just the end result of what the loop creates as I'm showing below.
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
var output = ""; // Will hold result
// Instead of a while loop, just a for loop that counts to the value entered into the input
for (var i = 0; i < input.value; i++) {
// Don't modify the DOM more than necessary (especially in a loop) for performance reasons
// Just build up a string with the desired output
output += "<p>Content</p>"; // Concatenate more data
};
// After the string has been built, update the DOM
document.getElementById("content").innerHTML = output;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
And, if you truly do want the same string repeated the number of times that is entered into the input, then this can be a lot simpler with string.repeat().
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
// Just use string.repeat()
document.getElementById("content").innerHTML = "<p>Content</p>".repeat(input.value);
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
As #ScottMarcus pointed out you had the following issues:
While Loops do not need a ; at the end of while(args) {}
Your .innerHTML code was in the wrong place
You had a typo in getElementById("numerInput") which I changed to getElementById("numberInput")
Code
function updatePage() {
// Get input value
var numberInput = document.getElementById("numberInput").value;
// Will be used to store all <p> contents
var template = "";
while (numberInput > 0) {
// Add all contents into template
template += "<p>Content<p/><br>";
numberInput--;
}
// Append upon clicking
document.getElementById("content").innerHTML = template;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
</div>

Delete button next to each array's value

I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW

Categories