making javascript variables keep their value - javascript

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');">

Related

Error with Javascript TypeError code, variable undefined

I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.

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);

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>

store value into an array JS

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.

angular-tags: Reset the tags input value

index.html
<div class="modal-header" >
<button type="button" class="close" ng-click = "submit(information.add, information.subject, information.emailContent); close()">×</button>
<h3>Compose Email</h3>
</div>
<div class="modal-body">
<form name = "form.email">
<tags options="{addable: true}" typeahead-options="typeaheadOpts" data-model="information.add" data-src="toPerson as toPerson for toPerson in to"></tags>
<input type="text" placeholder="Subject" style="width:95%;" data-ng-model = "information.subject"><br />
<textarea style="width:95%;" rows="10" data-ng-model = "information.emailContent"></textarea>
</form>
</div>
emailViewController.js
$scope.information = {
add: [],
subject: [],
emailContent: []
};
$scope.clear = function() {
if ($scope.information.add !== "") {
$scope.information = null;
}
};
I am setting the value of $scope.information to null. After doing this, the input box value bound to information.subject and the textarea value bound to information.emailContent are reset. However, the tags input value bound to information.add does not reset. Does anyone know why this is being caused.
I think $scope.remove() in the angular-tags widget should be used to remove the tag. I am not sure how to implement it though. Angular-tags source code can be found here - https://github.com/boneskull/angular-tags/blob/master/src/tags.js
Here is a plunker - http://plnkr.co/edit/PaG1k5N37BTOflObnN7K?p=preview
Attempt 1
This is a plunker of what I have tried so far - http://plnkr.co/edit/jjE2bU8zkkyw36rtAymL?p=preview . I am redefining the value of $scope.info to null in a function wrapped inside $timeout. I thought maybe the changes I made to the $scope are not being applied to the view, so I tried to wrap it in a $timeout. Doing so did not fix the problem though.
This code $scope.information = null; is supposed to nuke all your information and clear the entire thing? This only sets the reference to the object containing the arrays to null. The arrays are still there and still referenced by your widget I expect - (I'm not sure how the library you are using for your tags is implemented)
The below code actually empties the arrays:
$scope.information.add.length = 0;
$scope.information.subject.length = 0;
$scope.information.emailContent.length = 0;

Categories