How do I make text appear in text field with javascript? - javascript

I'm relatively new to JavaScript and I can't seem to figure out how to output text in a textfield in HTML. I've looked at many solutions and although I'm very close (I think I am), I still can't get it to function properly.
I'm trying to sort a series of numbers by separating them with "; " and wish to show the result in the bottom text field by ascending or descending order. The action is done by pressing the button to sort them.
When trying to debug it, it seems that the variables are being assigned their values as they should, but the variable "output" just won't show up in the "Sorted Numbers" textfield. My code is incomplete as I'm just trying to test this for an ascending order before I add in the descending order.
Here is my code...
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Sorting Numbers</title>
</head>
<body>
Enter Numbers Here: <input type = "text" id = "numInput"><br><br>
Select Option: <select id = "menu">
<option value = "ascending">Ascending</option>
<option value = "descending">Descending</option>
</select><br><br>
Sorted Numbers: <input type = "text" id = "numOut"><br><br>
<button onclick = "sortNums()">Sort Numbers</button>
<script type = "text/javascript">
function sortNums() {
var choice = document.getElementById("menu");
var numbers = document.getElementById("numInput").value;
var output = document.getElementById("numOut").value;
if(choice.value = "ascending") {
arr = numbers.split('; ').sort().join('; ');
output = arr;
}
}
</script>
</body>
</html>

Because you never assigned output to it afterwards:
if(choice.value = "ascending") {
arr = numbers.split('; ').sort().join('; ');
output = arr;
document.getElementById("numOut").value = output;
}

Related

Getting Array positions in HTML automatically

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.

for loop and innerHTML [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How do I populate some text with a paragraph using innerHTML? I need to enter a number into the textbox and then repeat some text as many times as the number entered into the textbox.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ex10.js</title>
</head>
<body>
<input type="text" id="input-type" onKeyUp="myFunction()">
<p id="sample-text">Here is some text</p>
<script>
function myFunction() {
let count = document.getElementById("input-type").value;
document.getElementById("sample-text").innerHTML = count;
if (isNaN(count)) {
document.getElementById("sample-text").innerHTML = "Error. Not a number";
}
else {
for(int i = 0; i < count; i++) {
document.getElementById("sample-text").innerHTML = "This is some text";
}
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ex10.js</title>
<script>
function myFunction() {
var count = document.getElementById("input-type").value;
if (isNaN(count)) {
document.getElementById("sample-text").innerHTML = "Error. Not a number";
}
else {
// create your empty array
var lines = "";
// loop x amount of times and add your text to the array
for (var i = 0; i < count; i++) {
lines = lines+"Atmiya\n";
}
// convert the array to a string, with each string on its own line
document.getElementById("sample-text").innerHTML = lines;
}
}
</script>
</head>
<body>
<input type="number" id="input-type" onKeyUp="myFunction()">
<p id="sample-text">Here is some text</p>
</body>
</html>
document.getElementById("sample-text").innerHTML = someVar;
This will completely overwrite the content of your html element every time you call it, which is probably your problem.
What you'll want to do instead is build your string beforehand, and then populate the element once afterwards. How about building an array, and then creating a string using join?
// create your empty array
var lines = [];
// loop x amount of times and add your text to the array
for (var i = 0; i < count; i++) {
lines.push("This is some text");
}
// convert the array to a string, with each string on its own line
document.getElementById("sample-text").innerHTML = lines.join("\n");
There are a few tricks to make it easier:
<input type="number">
<input> elements of type "number" are used to let the user enter a number. They include built-in validation to reject non-numerical entries. The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by simply tapping with a fingertip.
You can also use the += operator to concatenate to an element's innerHTML property.
onchange is probably better to use than onkeyup. I'm not sure onkeyup works with a touch screen. And the number input box has little controls to change the value.
function go() {
let text = document.querySelector('#sample-text').innerHTML;
let times = document.querySelector('#times').value;
let output = document.querySelector('#output');
let ix = 0;
output.innerHTML = '';
while (ix < times) {
output.innerHTML += text;
ix++;
}
}
<input type="number" min="1" id="times" onchange="go()">
<p id="sample-text">Here is some text</p>
<p id="output"></p>

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.

How to store and re-use text input values and variable values that use Math.random()?

Okay, so I'm trying to create a quiz application for revision purposes that asks a random question from a list of questions, takes a text input as the users answer to the question, and then compares it to the actual answer to the question. The code I have used is:
var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;
var answerValidation = function(correctAnswer, userAnswer) {
correctAnswer = htmlModule[ranPropName][1];
userAnswer = document.getElementById("submit").value;;
if(userAnswer === correctAnswer) {
document.getElementById("rightWrong").style.backgroundColor = "green";
} else {
document.getElementById("rightWrong").style.backgroundColor = "red";
}
};
The variable htmlModule refers to the object in which the questions and their answers are stored. Each question and answer pair is stored inside an array that is the value of its property, the property simply being a key used to reference each pair e.g. htmlQ1, htmlQ2 etc.
The main problem I seem to be having is that my if statement comparing the actual answer and the user answer won't evaluate to true. I know this because the background colour of the div element rightWrong only ever turns red, even when I've definitely typed in a correct answer at which point it should turn green. My assumption is that either the text input isn't being stored for some reason, or the value of the variable ranPropName that uses Math.random() is changing due to the use of Math.method(), but I'm stuck as to how to remedy either potential problem. Thanks in advance for any replies.
Well, I started to visualize your quiz as you explained.
One thing is need to be changed is that you get userAnswer from the value of an element with Id submit which I assume most probably it's an button tag, so I write a working code sample as follow:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
</head>
<body>
<input type="text" id="rightWrong" />
<div id="question" />
<button id="submit">Submit</button>
</body>
<script>
var htmlModule = {
'htmlQ1': ['1+1=?', '2'],
'htmlQ2': ['2+2=?', '4']
};
var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;
var answerValidation = function(correctAnswer, userAnswer) {
correctAnswer = htmlModule[ranPropName][1];
userAnswer = document.getElementById("rightWrong").value;
if(userAnswer === correctAnswer) {
document.getElementById("rightWrong").style.backgroundColor = "green";
} else {
document.getElementById("rightWrong").style.backgroundColor = "red";
}
};
</script>
</html>
Please share your html if you still face problems.

dropdown menu in javascript with adding new elements

I am new in javascript and in this moment I am trying to use "Basic DOM and JS". I am doing a dropdown menu, what gets his elements from an array. There is an input field, where you can add new items into the array.I also made a button to push and save the item into array and make the dropdown automatically with DOM.
My problem if you push the button, it makes always a new dropdown menu. Otherwise the array works good, but I need just one dropdown menu with the items of array. I think this problem comes out at listing with ul li too. Here is my whole code and thanks for helping
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
var menu = document.createElement("select");
document.body.appendChild(menu);
for(var i = 0; i<select.length; i++){
var option = document.createElement("option");
var text = document.createTextNode(select[i]);
option.appendChild(text);
menu.appendChild(option);
}
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
You are creating the select tag every time array() is invoked. So create select tag once and rest of the time create option tag when array() is invoked. Here is your solution.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
var selectIsCreated = false;
var menu;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
if(!selectIsCreated){
menu = document.createElement("select");
document.body.appendChild(menu);
selectIsCreated = true;
}
var option = document.createElement("option");
var text = document.createTextNode(select[select.length-1]);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
So Suman already answered your question, but in terms of simplifying the code or the approach, I think you could take a different approach by removing the use of the "select" array entirely. The array isn't necessary to add in the value to the select list, as you can get everything you need from the input element, so you just need to work on adding the option to the actual select DOM element.
Here is the desired functionality re-factored a bit with this in mind.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
function createSelect() {
select = document.createElement('select');
select.id = 'select';
document.body.appendChild(select);
return document.getElementById('select');
}
function addOption(){
var input = document.getElementById("input");
var value = input.value;
// This will attempt to grab the 'select' element, but if it finds
// that it doesn't exist (i.e. getElementById returns a "falsy" value)
// then it will return the value of the createSelect function.
// This could also be done with more explicit "if" statements
var menu = document.getElementById('select') || createSelect();
// The same effect could be achieved by running this code:
/*
var menu = document.getElementById('select');
// If the select element hasn't been created/added to the page yet,
// then the above call to getElementById will return a "falsy" value,
// i.e. a value that isn't a strict boolean type but JS will treat it
// as "false".
if (!menu) {
menu = createSelect();
}
*/
var option = document.createElement("option");
var text = document.createTextNode(value);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<!--
I've renamed the array() function since we don't even
have an array anymore
-->
<input onclick="addOption()" type="button" value="Add">
</body>
</html>
You can see this in action on this jsFiddle

Categories

Resources