JavaScript not printing to textbox - javascript

I am trying to make a web tool that takes user imputed values as a list of objects and a number of objects to randomly choose and then will print out the number of objects chosen from the list at random when the button is clicked. However i have not been able to get anything to print. I have tried to call the variables both with qoutes and without them and i still haven't gotten the compute to print any results in the final read only textbox. I think the issue is somewhere in my script functions but i cant figure out where and i've spent hours looking up syntax and possible issues to no avail. Ive tried to work with inner.html without success and the current method (document.getById....) is copied from http://www.mauvecloud.net/randomchooser.html that works to randomly choose one thing and print the result.
<html>
<style></style>
<head>
<title>Random Chooser</title>
<script>
Array.protoype.chooseFromArray() = function(){
var chosenIndex = Math.floor(Math.random() * ValueArray.length);
var elementPicked = ValueArray["chosenIndex"];
ValueArray.splice("chosenIndex",1);
return elementPicked;
}
function chooseRandomly(){
var ValueArray = document.getElementById("valuelist").value.split("\n");
var numItems = document.getElementById("items").value;
var ReturnArray = [];
for(i=0; i < numItems; i++){
var element = ValueArray.chooseFromArray();
ReturnArray.push("element");
}
document.getElementById("result").value = ReturnArray.toString();
}
</script>
<body>
Enter some values, one on each line, then click the choose button to pick randomly.
<form action onsubmit="return false;">
<textarea id="valuelist" rows="15" cols="60"></textarea>
<br>
<br>
Randomly choose <input type="number" id="items" > items
<br>
<input type="button" value="Choose" onclick="chooseRandomly();return false">
<br>
<br>
<input id="result" type="text" size="80" value readonly="readonly">
<br>
<br>
</form>
</body>
</html>

You're confused on a few JavaScript syntax points. I won't bother correcting the non-idiomatic style, you should read more about that here on your own once you understand the changes outlined below.
First, here's the cleaned up and fixed version so we can take a look at it together:
Array.prototype.chooseFromArray = function() {
var chosenIndex = Math.floor(Math.random() * this.length);
var elementPicked = this[chosenIndex];
this.splice(chosenIndex, 1);
return elementPicked;
}
function chooseRandomly() {
var ValueArray = document.getElementById("valuelist").value.split("\n");
var numItems = document.getElementById("items").value;
var ReturnArray = [];
for (var i = 0; i < numItems; i++) {
var element = ValueArray.chooseFromArray();
ReturnArray.push(element);
}
document.getElementById("result").value = ReturnArray.toString();
}
window.chooseRandomly = chooseRandomly;
First thing's first, to reference a function from HTML on JSFiddle you'll need it to be defined on the window. You don't normally need to do that, so you can mostly ignore that point.
Generally, you have several syntax errors.
Defining a property on an object (prototypes are objects (MDN)) happens just like variable assignment, so you just write object.<property_name> = value. You were calling chooseFromArray then assigning to that call (which is just invalid syntax).
When creating functions for prototypes, this will usually reference the object calling the function. In this case, any array calling chooseFromArray will have itself bound to the this reference inside the prototype function.
When accessing properties through the indexer you just pass the string. If it's a variable, you don't surround it with strings. Ex:
var chosenIndex = 123;
var elementPicked = this["chosenIndex"];
// This is the same as this.elementPicked;
var elementPicked = this[chosenIndex];
// This is what you want as you're accessing the `123` property on `this`
The same goes for passing variables to functions. You just pass the variable. Anything inside of 's, ' ` 's and "s are string literals and will not reference any variables.

Related

jQuery - Take array of objects, then sort based on a dataset

I have a game I created that will add questions missed to my array missedArr, in my JSFiddle example, I have 2 buttons (both set to be wrong answers). After clicking these, it seems to have stored both clicks correctly, however I want give a readout at the end of the game to show my user what parts they did well on vs ones they did poorly on.
To do this, I created a function called determineScorecard which should serve to create a dict of my missedArr, however, when it goes to trigger I get undefined.
The dSc function should be sorting across the data-category set on the html buttons, then I want to console.log only the ones that were missed in category-2
function determineScorecard (){
//build dictionary for missed questions
var sortedMissed = {};
for( var i = 0, max = missedArr.length; i < max ; i++ ){
if( sortedMissed[missedArr[i].category] == undefined ){
sortedMissed[missedArr[i].category] = [];
}
sortedMissed[missedArr[i].category].push(missedArr[i]);
}
console.log(sortedMissed["2"]);
}
I can't seem to get this to split up correctly.
I think this is what you're trying to do:
var incorrect = [];
$('.answer').click(function(){
var data = $(this).data(),
correct = data.correct;
if(!data.correct){
incorrect.push(data);
determineScorecard();
}
});
function determineScorecard(){
var missed = {};
for(var i = 0, max = incorrect.length; i < max ; i++){
var question = incorrect[i];
if(!missed[question.category]){
missed[question.category] = [];
}
missed[question.category].push(question);
}
console.log(missed);
}
DEMO
However, I don't see how this can produce what you're expecting. The scorecard logic makes zero sense to me (with the code that's been provided). Can you post a complete example with the questions so we can see the entire flow?
Maybe you want something like this?
var missedArr = [];
$('.answer').click(function(){
var da=$(this).data();
if (da.correct) return false;
missedArr.push(da);
determineScorecard();
});
function determineScorecard (){
var sortedMissed = {};
$.each(missedArr,(i,da)=>{
if( sortedMissed[da.category] === undefined ){
sortedMissed[da.category] = [];
}
sortedMissed[da.category].push(da);
})
console.log(JSON.stringify(sortedMissed));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="btn btn-danger answer" data-category="2" data-question="2" data-value="300" data-correct="false">Google</button>
<button class="btn btn-danger answer" data-category="3" data-question="2" data-value="300" data-correct="false">Full-circle reporting</button>
In my solution I have not stored the whole buttonDOM elements but only their data()-objects into the sortedMissed array since these contain all the information about the question and button pressed. But if you don't like it, feel free to change that back again ...
Referencing your JSFiddle: The missedArr array contains DOM elements. To get the category, value, etc of that element you'll need to access the dataset property of the element.
missedArr[i].category // doesn't exist
missedArr[i].dataset.category // should exist
Updated for jQuery, which uses the .data() method:
missedArr[i].data('category') // should exist
When wrapping 'this' in the jQuery function like $(this), the element becomes a jQuery object, so to access the dataset use the .data() method rather than trying to access the properties directly like you would with vanilla JS:
// lines 22 - 24 of your JSFiddle
if( sortedMissed[missedArr[i].category] == undefined ){
sortedMissed[missedArr[i].category] = [];
}

use a passed val in js

I need to pass a value from html and use it to find a var in my Js, so according to the value in theId on my html I could use the var in my js. How can I do that?
HTML
<input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist
<script> tag on HTML
function getToWork(theId){
usedCheckBox(theId);
}
myJs.js
function usedCheckBox(theId){
var temp1 = theId.name; - will be undefined
var temp2 = Waist.name; - will work
}
var Waist = {name:"bob",age:"17"}
The problem with your code is, you are not using document.getElementById as below:
JS:
document.getElementById("Waist").addEventListener("change",function(evt){
getToWork(this.id);
})
function getToWork(theId){
usedCheckBox(theId);
}
function usedCheckBox(theId){
console.log(theId);
console.log(Waist);
var temp1 = document.getElementById("Waist").val; // will return Waist
var temp2 = Waist.val(); // generate error, don't know what you want
}
var Waist = "change today!"
Fiddle:
https://jsfiddle.net/xLvzah8w/1/
I understood your question now and for that you should create one parent object as shown:
function usedCheckBox(theId){
var temp1 = parent[theId].name; // will return bob
console.log(temp1);
var temp2 = parent.Waist.name; // will return bob
console.log(temp2);
}
var parent = {
Waist : {name:"bob",age:"17"}
}
The reason why your code doesn't work is because you are trying to access property of a string. 'theId' is a string with value 'Waist' where Waist is an object so error occurs.
Updated fiddle: https://jsfiddle.net/xLvzah8w/2/
The correct way to proceed with this is:
In place of var temp1 = theId.val();
Use document.getElementById(theId).value
When you do: theId.val(), it makes sense that it's undefined. Calling getToWork(this.id) is sending a string, not an HTML element. Therefore calling .val() on a string is undefined.
If you're trying to get the text value stored in the checkbox element that was pressed, you need to change to ...
function getToWork(arg) {
console.log(document.getElementById(arg).value);
}
<input id="Waist" type="checkbox" value="INPUT_BOX" onchange="getToWork(this.id)"> Waist
You should avoid using the onclick attribute and rather listen for the event "js side" (addEventListener/attachEvent).
In the context of those eventhandlers, this generally represents the element the event listener has been attached to:
document.getElementById("Waist").addEventListener("change",getToWork);
function getToWork(){
usedCheckBox(this);
}
function usedCheckBox(elem){
var value = elem.value ;
}

Create javascript variable with button click no jQuery

I am wondering how I would create a variable on the click of a button, so I could make a random name generator, like this:
<input class="varValue" placeholder="Name to be generated">
<button class="createVar></button>
<script>
var createVar = document.querySelector(".createVar");
var varValue = document.querySelector(".varValue");
var nameNumber = 0;
var getValue = function(){
varValue.value = //new var with ascending values or something;
nameNumber = nameNumber + 1;
};
createValue.addEventListener("click", getValue(), false");
//then some Math.random using, nameNumber, anyway I'll figure it out
</script>
So how would I make the variables on the click of the button?
Also no jQuery please.
The function getValue() [which I don't see declared, so it should be declared somewhere] is in charge of any new logic attached to that event in this case.
To create and do something with those variables simply do it right inside that function.
I believe you meant createVar.addEventListener() and not createValue

.innerHTML Not Displaying While Using a For Loop

I am attempting to write a script that will allow users to input numbers into a screen, add them to an array and then print the values on an innerHTML element.
However, when I attempt to use it in a for loop, nothing is printing out and it goes to a new page where the only thing displayed is the first number entered.
I am new at JavaScript and might be doing it incorrectly. Please let me know!
Thanks in advance
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
count++;
}
function printValues() {
for (i = 0; i < a.length; i++) {
document.write(a[i], " ").innerHTML = array;
}
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
<a id="array"></a>
</p>
From MDN:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So your problem is caused by document.write. Once you write to your already loaded document, everything else is thrown away, including your javascript. (You had other problems too with just how you were using it, but this is the main problem).
You have an element with the id array, which I assume is where you want to put your numbers. So you need to get that element with getElementById and then set its innerHTML. You can use array.join to avoid the loop.
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
count++;
}
function printValues() {
document.getElementById('array').innerHTML = a.join(",");
}
<input type="text" id="input">
<br>
<input type="button" onclick="addNum();" value="Add Number">
<br>
<input type="button" onclick="printValues();" value="Print Numbers">
<p>
<a id="array"></a>
</p>
A couple of other things you should look at. After adding a number in addNum, you should probably clear the text box by setting the value to null. Secondly, it's preferred to add event handlers in code rather than in your HTML.
function printValues() {
var strValues=''; // Initialize a temporary variable
for (i = 0; i < a.length; i++) {
strValues += a[i] + ' ';
}
document.write(strValues); //Writting variable to document.
}
In the above example we have create a temporary variable and sets the default value to blank. Then in for loop we concatenate the array value to variable using += sign.
What you are doing is not the correct way of setting stuff up in innerHTML . Also, you are not retaining the values to be printed on to the screen. Everytime , you click on print the new value inputted by the user is just getting passed and the old value is getting replaced with the new one . Here the variable valueToBePrinted will always remember the last value that was inputted as it concatenates all the inputted values to it, once the user is done with his/her input .
Look at the following piece of code :
var a = [];
var count = 0;
function addNum() {
a[count] = document.getElementById('input').value;
console.log(a[count]);
count++;
}
function printValues() {
var valueToBePrinted='';
for (i=0;i<a.length;i++) {
valueToBePrinted += a[i] + ' ';
console.log(valueToBePrinted)
document.getElementById('array').innerHTML =valueToBePrinted;
}
}
Also , look at the result in the Fiddle here : Fiddle
The statement "document.write(a[i], " ").innerHTML = array;" is wrong.
There is no variable named array declared in the code.
The correct form to print all the numbers using document.write is,
for (i=0;i<a.length;i++) {
document.write(a[i] + " ");
}
If you need sum of all input numbers and the print the sum, then you can simply sum it up in a variable as you click addNumber button as,
var total = 0;
function addNum() {
total += Number(document.getElementById('input').value);
}
function printValues() {
document.write(total);
}
You typically would not use a "count" variable to add items to an array but would instead push to the array however I kept it in case you needed it otherwise.
You would as others noted not do a document.write to an element but instead use the innerHTML and replace or append to that.
Odd also that you are putting the innerHTML in a link <a /> element but since that is what you are using I will reproduce that.
IF you do want to use these as number (integers?) you would want to parse them with parseInt(string, radix); or parsefloat.
You did not have i set as a variable object so I did that here
Slightly reworked code here:
var a = [];
var count = 0;
function addNum() {
a.push(parseInt(document.getElementById('input').value, 10));
count++;
}
function printValues() {
var i;
var myValues = "";
for (i = 0; i < a.length; i++) {
myValues = myValues + a[i] + " ";
}
var element = document.getElementById("array");
element.innerHTML = myValues;
}
Here is the code reproduced as a working example: http://jsfiddle.net/coffw8tg/

How to Get back stored data in LocalStorage HTML 5 in form of array?

This Code works to Give me stored cars Name
<html>
<head>
<script type="text/javascript">
var carArray=[];
function addToListCarArray(){
var newCarName=document.getElementById('carName');
carArray.push(newCarName.value);
if(window.localStorage){
localStorage.setItem("carNameKey",JSON.stringify(carArray));
}
}
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
carNames = JSON.parse(carNames);
for (i=0;i<carNames.length;i++){
alert(carNames[i]);
}
}
}
</script>
<title>Local Storage Demo</title>
</head>
<body>
<h1>Demo of Local Strorage</h1>
<div>
<input type="text" id="carName" name="carName"> </input>
<button onclick="addToListCarArray()">Add Car</button>
<button onclick="readCarNames()">Display</button>
<p id="displayCarNames"></p>
</div>
</body>
</html>
But how can i get the stored car names in form of an array and display it. I tried modifying the readCarNames() function in two ways but none of them worked.
I searched but everywhere it's all about passing the object and storing which i'm able to do but not able to retrieve it in form of an array and then print it
here is what i tried to work out but didn't worked (Edit: didn't worked out because of my Wrong Style of coding unfortunately)
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
var resultCarNames[]=JSON.parse(carNames);
resultCarNames.toString();
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
and the second one that i attempted but didn't worked .
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
carNames = JSON.parse(carNames);
var resultCarNames[];
for (i=0;i<carNames.length;i++){
resultCarNames.push(carNames[i]);
}
resultCarNames.toString();
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
EDIT: As pointed out the mistake i made by the veproza in Answer I was able to solve this ..
Here is the working snippet
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
var resultCarNames=JSON.parse(carNames);
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
}
In your first snippet, you seem to have it working correctly. By the line
carNames = JSON.parse(carNames);
you have the array of strings in carNames variable. After all, you iterate on it in the following for loop. You can try it by adding a line printing it, e.g.
alert(carNames);
If you want to print it to an element, you may want something like this:
document.getElementById('displayCarNames').innerHTML = carNames;
So your basic print array variable to an element would look like this:
function readCarNames(){
var storedString = localStorage.getItem("carNameKey");
var parsedArray = JSON.parse(storedString);
alert(parsedArray);
document.getElementById('displayCarNames').innerHTML = parsedArray;
}
Now, why it doesn't work in your code: In your second and third snippets, you need to know that in JavaScript, you don't initialize an array variable with var arr[]. You just say var arr = [] or var arr = JSON.parse(string). So this
var resultCarNames[]=JSON.parse(carNames);
should actually be just
var resultCarNames=JSON.parse(carNames);
and then it'll work.
Also note that variable.toString() returns a new variable, but does not change the original variable. Example:
var a = [1, 2, 3];
var b = a.toString();
console.log(a); // [1, 2, 3] - an array
console.log(b); // "1,2,3" - a string
So in your code, the line resultCarNames.toString(); doesn't do anything at all. Still, when assigning a variable to a DOM node via .innerHTML, it gets converted to String automatically.
The third snippet contains the same mistake with improper initialization. This time, the line var resultCarNames[]; should be var resultCarNames = [];. Other than that, you have a bit of a mess with curly braces, as you're missing the one closing the for cycle.

Categories