Getting Array positions in HTML automatically - javascript

I have many arrays some upto 60 some upto 100. I am trying to get the text at the 0 position of this arrays for all arrays. I am sorry I don't know how to frame the question correctly. I don't want to type (greeting[0])[1] etc for say 100 times for every greeting. This is my code so far. Can someone help me in this! The greeting[0] etc actually go till 60 etc. Is it possible to do something like let i = 0 , for greeting.length , if i < greeting.length , i++ , and somehow put (greeting[i][0]}. And the result will be such that it show the values of all greeting shows in the paragraph element or in a separate window or something. I am still new to HTML so forgive me is if this seems basic.
Edited Question Update.
P.S. Some of my Arrays have the format greeting[0] = new Greet["Hola", "Salve", "Olá"] . I had to do it such because I use the three options. Is there any way I can automate the process with this?
Edited Question - Update 1
So I have updated the code to be more representative of what I am trying to ask. Basically here I want to provide a button so that on clicking the button I can see all the English words I can choose from. So I want to do something like get the value of the English words in greeting 0, 1 etc and display them separately so that we can select which English word we want instead of just numbers which we don't know what word they represent. Can someone help me with this please!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="English"> Select English Word </p>
<p id="French"> Click below button </p>
<p id="Italian"> Click below button </p>
<button onclick="Another()"> CLick </button>
<script type="text/javascript" src="./script.js"></script>
</body>
</html>
var greeting = [];
greeting[0] = new Word("Hi", "salut", "Ciao") ;
greeting[1] = new Word("Hello", "Salve", "Ciao") ;
greeting[2] = new Word("Welcome", "Bienvenue", "benvenuta") ;
greeting[3] = new Word("Good Day", "Bonne journée", "Buona giornata") ;
greeting[4] = new Word("Good Day", "Bonjour", "Buongiorno") ;
function Word(English,French,Italian) {
this.English = English ;
this.French = French ;
this.Italian = Italian ;
} ;
function Another() {
var nums = window.prompt("Select a number within " + greeting.length ) ;
var optionuser = greeting[nums] ;
var selection = alert("You selected English word " + optionuser.English )
document.getElementById("English").innerHTML = optionuser.English ;
document.getElementById("French").innerHTML = optionuser.French ;
document.getElementById("Italian").innerHTML = optionuser.Italian ;
}

I recommend using Array.map(callback) (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
document.getElementById('something').innerHTML = greeting.map(item=>item[0]).join("<br>");

I have given a slightly modified code below.Hope this is what you are looking for. Since you are new, one advise is not to use window.prompt in your code. Explore some other way. Also change the function Word to Class Word. I think you were trying to create a Class but have given wrong keyword. Instead of prompt, I have used radio button.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Language:</p>
<input type="radio" id="English" name="language" value="English">
<label for="English">English</label><br>
<input type="radio" id="French" name="language" value="French">
<label for="French">French</label><br>
<input type="radio" id="Italian" name="language" value="Italian">
<label for="Italian">Italian</label><br>
<input type="radio" id="Spanish" name="language" value="Spanish">
<label for="Spanish">Spanish</label><br>
<button onclick="Another()">Click</button>
<p id="msg"></p>
<script>
class Word {
constructor(English,French,Italian){
this.English = English ;
this.French = French ;
this.Italian = Italian ;
}
} ;
var greeting = [];
greeting[0] = new Word("Hi", "salut", "Ciao") ;
greeting[1] = new Word("Hello", "Salve", "Ciao") ;
greeting[2] = new Word("Welcome", "Bienvenue", "benvenuta") ;
greeting[3] = new Word("Good Day", "Bonne journée", "Buona giornata") ;
function Another() {
let optionSelected = document.querySelector('input[name="language"]:checked').value;
document.getElementById('msg').innerHTML += 'You selected:'+optionSelected;
for(let i=0;i<greeting.length;i++){
document.getElementById('msg').innerHTML += '<br>' + greeting[i][optionSelected];
}
}
</script>
</body>
</html>
Note: Use separate .js file as you did. For answering purpose i have used inline style.

Related

Why isn't this JavaScript code executing?

Sorry, I'm a student and I can't figure out what is wrong with my code! When I click the buttons absolutely nothing happens. I've tried isolating each function and still nothing happens. I've been looking it over for ages trying to find a missing tag or a missing bracket or parentheses or something but I'm not finding it. It's meant to create a mini-blog simulation. You should be able to add an entry to the top of the list with the first function, and you should be able to delete an entry of your choice with the second function. Thank you for any help!
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 5 Activity</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Awesome NBA Blog! Each day, a sentence about the feats of a different legend!</h1>
<ol id="playerEntries">
<li>Michael Jordan: 6 Championship rings in 6 NBA Finals appearances.</li>
<li>Bill Russell: 11 time champion in a 13 year career, including one as a player/head coach.</li>
<li>Kobe Bryant: 5 Championships, 18-time All-Star.</li>
<li>Lebron James: Won a Championship and was the Finals MVP with 3 different teams.</li>
</ol>
<form action="">
Add a new entry:
<input type="text" name="newEntry" id="newEntrySpot" size="80">
<input type="submit" value="Submit" onclick="addEntry()"><br>
Delete an entry(which entry would you like to delete?)
<input type="number" name="entryNum" id="numToDelete">
<input type="button" value="Delete" onclick="deleteEntry()"><br>
</form>
<script type="text/javascript">
function addEntry() {
var newEntry = document.getElementById("newEntrySpot").value;
var newestEntry = document.createElement("li");
newestEntry.innerHTML = newEntry;
var blogList = document.getElementsByTagName("ol")[0];
var topEntry = document.querySelectorAll("#playerEntries li")[0];
blogList.insertBefore(newestEntry, topEntry);
}
function deleteEntry() {
var num2Delete = document.getElementsByName("entryNum")[0].value;
var blogList = document.getElementsByTagName("ol")[0];
var howManyEntries = blogList.length;
if (howManyEntries >= 1) {
var postToDelete = blogList[num2Delete - 1];
var deletedPost = blogList.removeChild(postToDelete);
}
}
</script>
</body>
</html>
You have to replace
<input type="submit" value="Submit" onclick="addEntry()"><br>
with
<input type="button" value="Submit" onclick="addEntry()"><br>
otherwise the form will be submitted and the page will reload. You can also use the submit function of the form but will you have to use preventDefault.
Also to make the deleteEntry function works, you can't use document.getElementsByTagName("ol")[0]; since you can't use .length on an element. Here's another way to do it :
function deleteEntry() {
var num2Delete = document.getElementsByName("entryNum")[0].value;
var blogList = document.querySelectorAll("ol > li");
var howManyEntries = blogList.length;
if (howManyEntries >= 1) {
var postToDelete = blogList[num2Delete - 1];
postToDelete.remove();
}
}

JavaScript in HTML code: Random numbers are not evenly distributed

I've got the following problem:
I'm uploading a survey on amazon mturk using Python and the survey is done via HTML and javascript. I show one of three different versions of the survey to participants, which I select by generating a random number via javascript. I store the number in local storage to prevent refreshing the website from resetting it. The problem I find is that more people seem to get versions 1 than version 3. But I cannot recreate the problem for myself when running the code in Tryit Editor online.
Could you please help me understand (and fix) why this happens? The following is the (trimmed) HTML code that I upload. I replaced text and removed fluff.
<HTMLQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd">
<HTMLContent><![CDATA[
<!-- YOUR HTML BEGINS -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<script>
function test(){
document.getElementById('txt-field').value = "1";
}
</script>
</head>
<body>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'><input type='hidden' value='' name='assignmentId' id='assignmentId'/>
<span>
<INPUT TYPE="text" NAME="link_click" id='txt-field' value="0" style="display: none">
<div><h3><a href="www.google.com" target="_blank" id='report420' onclick="test()" >link</a></h3>
Instructions</div>
<div><table border="1" style="height: 258px;" width="196"><tbody>Table</tbody></table></div>
</span>
<!--I think the relevant part starts here-->
<script>
document.write("Miscellaneous question");
var i = localStorage.getItem('i') || Math.floor(3*Math.random());
localStorage.setItem('i',i);
if (i==0){
document.write("Version 1");
}
if (i==1){
document.write("Version 2");
}
if (i==2){
document.write("Version 3");
}
document.write("Miscellaneous question");
</script>
<p><input type='submit' id='submitButton' value='Submit' /></p></form>
<script language='Javascript'>turkSetAssignmentID();</script>
</body></html>
<!-- YOUR HTML ENDS -->
]]>
</HTMLContent>
<FrameHeight>600</FrameHeight>
</HTMLQuestion>
The random function Math.floor(3*Math.random()) has uniform distribution, but I don't think that 400 samples are enough so that you can see it in action (as #desoares mentioned).
Testing code:
var count = [0, 0, 0];
var n = 1000000;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
var count = [0, 0, 0];
var n = 400;
document.write('Testing for ' + n + ' samples : ');
for (var i = 0; i < n; i++) {
count[Math.floor(3*Math.random())]++;
}
document.write(JSON.stringify(count));
Also, if you want to be sure that people from the same computer are not forced to take the same version, you should clear the saved variable localStorage.removeItem('i'); on submit. You may also add an expiration mechanic.

Substring assignment

I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.

Removing lines containing specific words in javascript

This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}

Form button keeps showing results in new window

Very new to html and javascript here. I get the following form up and it calculates correctly but the result shows up in a new page. I'd like it to stay in the same page. Not sure what I did wrong here. Also, is there any way to shorten the function? Seems like a lot of work to do a simple calculation. Any help would be great.
<html>
<head>
<title>Help!</help>
<script type="text/javascript">
function add(x,y){
var x = document.add1.add2.value;
var y = document.add1.add3.value;
var x = Number(x);
var y = Number(y);
var z = x+y;
return (z);
}
</script>
</head>
<body>
<h3>Help me stack overflow you're my only hope!</h3>
<form name="add1">
Input first number to add: <input type="number" name="add2">
2nd number: <input type="number" name="add3">
<input type="button" value="Result"
onclick = "document.write('The total is: ' + add() + '.');" />
</body>
</html>
Dont' use document.write to display data, it overwrites entire document. You don't want that. It's better to create new function which would render result into some other element:
<input type="button" value="Result" onclick="showResult('The total is: ' + add() + '.');" />
and the showResult function can be for example:
function showResult(result) {
document.getElementById('result').innerHTML = result;
}
HTML:
<div id="result"></div>
Demo: http://jsfiddle.net/7ujzn35c/
Here are also a couple of general improvements you can make your code:
move string manupulations to showResult completely:
<input type="button" value="Result" onclick="showResult()" />
http://jsfiddle.net/7ujzn35c/1/
call add from inside showResults
onclick="showResult(this.form.add2.value, this.form.add3.value)"
http://jsfiddle.net/7ujzn35c/2/
<title>Help!</help>
First of all, This should be <title> Help! </title>
Secondly, document.write function actually starts writing the entire page anew.
You should either replace onclick = "document.write('The total is: ' + add() + '.');" with
onclick = "alert('The total is: ' + add() + '.');"
Better still, you could create a div element like so
<title> Help! </title>
<script>
.....
</script>
</header>
<body>
<div id = 'output'> </div> ...
then
`onclick = "document.getElementById("output").innerHTML = 'The total is: ' + add() + '.';"
And don't give up. Hope this helps you

Categories

Resources