document.getElementById no line feed - javascript

I've just started trying to learn javascript and have hit a problem.
The following code I expect to see my input box and button followed by 1,2,...10. Each number on a new line. What i get is the number 10 right below the box. I don't see the numbers 1,2,...9
<html>
<head>
<title>Test</title>
</head>
<style>
#pastetext {
color: blue;
font-weight: bold;
}
.enter {
border: 2px solid blue;
width: 200px;
height: 50px;
}
</style>
<script type="text/javascript">
function abc() {
intext = document.getElementById("pastetext").value;
for (i = 1; i < 11; i++) {
document.getElementById("answer").innerHTML = i;
}
}
</script>
<body>
<input type="text" name="enter" class="enter" value="" id="pastetext" />
<input type="button" id="btn" value="Click to Enter Data" onclick="abc();" />
<div id="answer" style="color:red; padding-left:100px;">
</div>
</body>
</html>
What i get is this:enter image here

You're setting the innerHTML property over and over again. Setting that properly completely replaces the previous content.
You could append the text:
function abc(){
var intext = document.getElementById("pastetext").value;
var answer = document.getElementById("answer");
answer.innerHTML = "";
for(var i=1; i <11; i++){
answer.innerHTML += i + " ";
}
}
Note that the local variables in your function should be declared with var.

Related

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

HTML paragraph isnt going into a straight line

I'm kinda new to programming and I cant solve this problem. The paragraphs are coming out like a stair case.
p
p
p
p
p
The p's are examples, but here is all the code I have done so far.
Keep in mind I'm not the best at css(I'm still learning)
All help would be appreciated
Please show me on how I an fix this problem, and tell me where in my code is this problem occurring.
I tried google but couldn't find anything...
var house = {}
function House() {
var msg = 'This house is painted'
var bath;
var bed;
var cook;
var Paint = document.getElementById('paint').value;
var square = document.getElementById('Square').value;
var bath = document.getElementById('bath').value;
var bed = document.getElementById('Bed').value
var cook = document.getElementById('Cook').value;
//Get paragraphs to store values
var paint = document.getElementById('isPaint');
var squareFeet = document.getElementById('sq_Feet')
var bathRoom = document.getElementById('bathroom')
var bedRoom = document.getElementById('BedRoom')
var kitchen = document.getElementById('kitchen');
if(Paint == 'Yes' || Paint == 'yes') {
house['isPainted'] = true;
paint.innerHTML = msg;
}
else if(Paint == 'No' || Paint == 'no') {
house['isPainted'] = false;
var msg = 'this house is not painted'
paint.innerHTML = msg;
}
else if(Paint == '') {
house['isPainted'] = undefined;
var msg = 'no details given';
paint.innerHTML = msg;
}
if(square != '' ) {
var squareFeetMsg = 'the house is';
squareFeet.innerHTML = squareFeetMsg + ' ' + document.getElementById('Square').value + ' square feet';
house['squareFeet'] = document.getElementById('Square').value
}else {
var squareFeetMsg = 'No Details Given';
squareFeet.innerHTML = squareFeetMsg;
}
}
body {
width: auto;
height: auto;
}
#houseDtails{
width: 350px;;
}
#container {
width: auto;
height: auto;
}
.houseDetails {
height: 0px;
float: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>House App</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div id="conatainer">
<div id="houseDtails">
<label for="paint">Is this house painted: </label><br>
<input type="text" id="paint" class="Detail" /><br>
<label for="Square">How many SQ feet does this have? :</label>
<input type="text" id="Square"><br>
<label for="bath">How many bathrooms does your house have</label>
<input type="text" id="bath"><br>
<label for="Bed">How many bedrooms dos your house have</label>
<input type="text" id="Bed"><br>
<label for="Cook">Does your house have a kitchen</label>
<input type="text" id="Cook"><br>
<input type="submit" name="" id="sub" class="subm" onclick="House()">
</div>
<div id="addDetailsToPage">
<p id="isPaint" class="houseDetails"></p>
<p id="sq_Feet" class="houseDetails"></p>
<p id="bathroom" class="houseDetails"></p>
<p id="Bedroom" class="houseDetails"></p>
<p id="Kitchen" class="houseDetails"></p>
</div>
</div>
<script src="House.js"></script>
</body>
The reason for the paragraphs rendering in that manner is result of float set on .houseDetails.
.houseDetails {
height: 0;
float: right;
}
This is because you have float: right; in your CSS for .houseDetails. Remove it and you should have your p aligned on the left below one another

using for loop to create html elements

What is wrong with my code? It is supposed to create input tags in html with using the incoming number (quantity):
// Declare variables
var numberOfGrades = 0;
var NL = "\n";
// Functions
function setQuantity() {
numberOfGrades = document.getElementById("quantity").value;
var inputBox = document.createElement("INPUT");
var BR = document.createElement("br"); // Break line
var gradeNumber = 1;
var gradeText = document.createTextNode("Grade " + gradeNumber + ":");
for (var i = 0; i < numberOfGrades; i++) {
alert(numberOfGrades);
document.getElementById("formDiv").appendChild(BR);
document.getElementById("formDiv").appendChild(gradeText);
document.getElementById("formDiv").appendChild(inputBox);
gradeNumber++;
}
}
body {
font-family: "Open Sans", sans-serif;
}
.container {
width: 100%;
background-color: lightcyan;
padding: 10px;
}
<body>
<h1>Homework and Quiz average calculator</h1>
<p>Please Enter the required information to calcuate</p>
<div class="container" id="formDiv">
<form id="formID">
<p>
<strong>Calculate the average of homework grades</strong>
</p>
How many grades?
<input type="number" id="quantity" name="quantity" min="1" max="10" value="1">
<!--<input onclick="setQuantity()" type="submit" value="Apply">-->
</form>
<button onclick="setQuantity()">APPLY</button>
<br>
</div>
<script src="script.js"></script>
</body>
JSFiddle here
When you call x.appendChild(y) the node y is added as a child from x removing it from where it was if already in the DOM.
For example:
var x = document.createElement("div");
var y = document.createElement("div");
var z = document.createElement("div");
x.appendChild(y);
z.appendChild(y); // now y is not inside x any more, was **moved** to z
If you want to have multiple nodes you need to create them inside the loop.

JavaScript Scope - populating text box with multiple selections

I'm sorry for asking a question that I'm sure is simple but I'm stuck. I have a project that requires the user to select 3 notes, the value for each should populate in the text box until the 3rd is entered. After that a compare is done to an array and a notification sent to the user letting them know if they have made a valid selection or not.
The problem I'm having is getting all 3 to populate, each time I click a button it overwrites the existing value. I've tried to push them to an array but it only contains the current value, I've tried a loop but that populates the selection 3x. I'm sure I'm overlooking something simple but have not been able to figure out what it is. Can someone point me in the right direction?
Thanks!
<!doctype html>
<html>
<head>
<title> Scope </title>
<meta charset="utf-8">
<style>
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
font-family: Helvetica, sans-serif;
}
div#container {
margin: auto;
width: 300px;
}
form {
margin-top: 20%;
}
form input[type="text"] {
font-size: 120%;
text-align: center;
}
form input[type="button"] {
background-color: lightblue;
font-size: 110%;
}
</style>
<script>
function addNote(event) {
var validChords = {
C: "CEG",
F: "FAC",
G: "GBD"
};
var note = event.target.value;
console.log(note);
var getNotes = [];
var noteDisplay = document.getElementById("notesDisplay");
var displayMessage = document.getElementById("message");
getNotes.push(note);
console.log(getNotes);
noteDisplay.value = getNotes;
noteDisplay.innterHTML = getNotes;
displayMessage.innterHTML = "Please Enter Antoher Note!";
//Code below is different things I've been playing with trying to
// figure this out.
// var success = false;
// if (notes.length > 0) {
// if (note) {
// for (var i =0; i < 3; i++) {
// if(notes[i] == note) {
// var found = true;
// getNotes.push(note);
// }
// }
// }
// }
// if (getNotes.length < 3) {
// }
}
window.onload = function() {
var notes = ["C", "D", "E", "F", "G", "A", "B"];
var cButton = document.getElementById("c");
cButton.onclick = addNote;
var dButton = document.getElementById("d");
dButton.onclick = addNote;
var eButton = document.getElementById("e");
eButton.onclick = addNote;
var fButton = document.getElementById("f");
fButton.onclick = addNote;
var gButton = document.getElementById("g");
gButton.onclick = addNote;
var aButton = document.getElementById("a");
aButton.onclick = addNote;
var bButton = document.getElementById("b");
bButton.onclick = addNote;
// your code here
}
</script>
</head>
<body>
<div id="container">
<form>
<p id="message">Enter a major triad chord:</p>
<p>
<input id="notesDisplay" type="text" size="21">
</p>
<p>
<input id="c" type="button" value="C">
<input id="d" type="button" value="D">
<input id="e" type="button" value="E">
<input id="f" type="button" value="F">
<input id="g" type="button" value="G">
<input id="a" type="button" value="A">
<input id="b" type="button" value="B">
</p>
</form>
</div>
</body>
</html>
I finally figured out how to get the entries and compare to the object containing specific values and return either a note or a message to try again. I'm almost there but am having an issue with my loops (I think). When a button is clicked a message is supposed to display saying "please enter another note" until the 3rd selection is made, when the first button is clicked I'm getting the "you have made an invalid selection message" and I don't understand why. The last piece I'm missing is the form is supposed to clear after either message is displayed. This is driving me nuts, can someone give me a hint as to what I still have wrong? Thanks!
Revised Code:
Scope
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
font-family: Helvetica, sans-serif;
}
div#container {
margin: auto;
width: 300px;
}
form {
margin-top: 20%;
}
form input[type="text"] {
font-size: 120%;
text-align: center;
}
form input[type="button"] {
background-color: lightblue;
font-size: 110%;
}
//Array to hold notes entered by user, counter to hold number of
//buttons clicked
var getNotes = [];
var counter = 0;
//addNote function, collects the notes entered by the user and displays
//them in the text box. When the number of notes entered equals 3 a
//compare is done to the validChords object. If the notes equal a valid
//chord a messages is displayed to the user telling them which chord was
//entered, if the chord is not correct a message is displayed telling
//them to try again. After either the form should be cleared.
function addNote(event) {
var validChords = {
C: "CEG",
F: "FAC",
G: "GBD"
};
var note = event.target.value;
var noteDisplay = document.getElementById("notesDisplay");
var displayMessage = document.getElementById("message");
if (counter <= 3) {
getNotes.push(note);
var removeComma = "";
for (i = getNotes.length-1; i >=0; i--) {
removeComma = getNotes[i]+removeComma;
}
noteDisplay.value = removeComma;
noteDisplay.innerHTML = removeComma;
displayMessage.innerHTML = "Please Enter Antoher Note!";
counter = counter+1;
}
if (counter == 3) {
for (var prop in validChords) {
if (removeComma === validChords[prop]) {
displayMessage.innerHTML = "You have entered a " + prop + "
Chord!";
notesDisplay.innterHTML = " ";
counter = 0;
}
}
} else {
displayMessage.innerHTML = "You have not entered a valid chord,
please try again!";
notesDisplay.innterHTML = " ";
counter = 0;
}
}
window.onload = function() {
var notes = ["C", "D", "E", "F", "G", "A", "B"];
var cButton = document.getElementById("c");
cButton.onclick = addNote;
var dButton = document.getElementById("d");
dButton.onclick = addNote;
var eButton = document.getElementById("e");
eButton.onclick = addNote;
var fButton = document.getElementById("f");
fButton.onclick = addNote;
var gButton = document.getElementById("g");
gButton.onclick = addNote;
var aButton = document.getElementById("a");
aButton.onclick = addNote;
var bButton = document.getElementById("b");
bButton.onclick = addNote;
}
</script>
</head>
<body>
<div id="container">
<form>
<p id="message">Enter a major triad chord:</p>
<p>
<input id="notesDisplay" type="text" size="21">
</p>
<p>
<input id="c" type="button" value="C">
<input id="d" type="button" value="D">
<input id="e" type="button" value="E">
<input id="f" type="button" value="F">
<input id="g" type="button" value="G">
<input id="a" type="button" value="A">
<input id="b" type="button" value="B">
</p>
</form>
</div>
</body>
</html>
I believe it's because you initialize getNote to an empty array every time you call the addNote function, check if that is the problem.
Thanks

How do I add textboxes dynamically in Javascript?

By default I have 5 textboxes. When a user clicks on a button, one textbox should be added.
How could I do this?
If you replace the innerHTML, the previously entered values will be cleared, to avoid that, you can append the input elements programmatically:
var input = document.createElement('input');
input.type = "text";
//...
container.appendChild(input);
Check this example.
Javascript Function
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Create Labels
var label = document.createElement("Label");
label.innerHTML = "New Label";
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
element.setAttribute("style", "width:200px");
label.setAttribute("style", "font-weight:normal");
// 'foobar' is the div id, where new fields are to be added
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(label);
foo.appendChild(element);
}
Html part,
<button id="button" value="Add" onClick:"javascript:add();">
And, Its done!
<script>
function add()
{
document.getElementById("place").innerHTML="<input type='text' value=''>"
}
</script>
<input type="button" value="clickMe" onClick="add();">
<div id="place"></div>
<script>
function add()
{
var inpt = document.getElementById('input_template');
inpt.parentNode.appendChild(inpt.cloneNode(false));
}
</script>
<input type="button" onclick="add();">
set id=input_template to one of the predefined textboxes
Best would be to attach an event on to the onclick of the button, that will set a div's visibility to inline. This is about the best way I can see for this, considering flexibility and robustness.
Have a look here for example code.
try this
<html>
<head>
<title>Dynamic Form</title>
<script language="javascript" type="text/javascript" >
function changeIt()
{
createTextbox.innerHTML = createTextbox.innerHTML +"<br><input type='text' name='mytext' >"
}
</script>
</head>
<body>
<form name="form">
<input type="button" value="clickHere" onClick="changeIt()">
<div id="createTextbox"></div>
</form>
</body>
</html>
by change for loop values we can generate textboxes dynamically
function addFunction() {
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = rowlen;
var arr = ['textboxfiledname'];
for (i = 0; i < 2; i++) {
var x = row.insertCell(i)
if (i == 1) {
x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
} else {
x.innerHTML = "<label>" + arr[i] + ":</label><input type='textbox' name='" + arr[i] + "'>"
}
}
}
function removeCell(rowid) {
var table = document.getElementById(rowid).remove();
}
input[type=text] {
width: 100%;
height: 50%;
padding: 15px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
label {
padding: 12px 12px 12px 0;
display: inline-block;
font-family: sans-serif;
}
input[type=button] {
background-color: #4CAF50;
border: none;
color: white;
padding: 6px 20px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset style="margin-left:20%;margin-right:20%;font-family:sans-serif;padding:15px;border-radius:5px;background:#f2f2f2;border:5px solid #1F497D">
<legend style="background:#1F497D;color:#fff;padding:5px 10px;font-size:22px;border-radius:5px;margin-left:20px;box-shadow:0 0 0 5px #ddd">DynamicTextbox</legend>
<table id="textbox">
<tr>
<td>
<input type="button" onclick="addFunction()" value="AddTextbox" />
</td>
</tr>
</table>
</fieldset>
The best I can help is with this code
<html>
<head>
</head>
<body>
<input type=text id="chat" placeholder="Enter a message..." maxlength="120">
<input type=Button id="Button" value="Test" onClick="T()">
<h1 id="message"></h1>
<script>
function T() {
var m = document.getElementById("chat").value
document.getElementById("message").innerHTML = m
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="myFunction()">Click me!</button>
<script>
var count =0;
function myFunction() {
count++
document.write('Lable1');
document.write('<input type="text" name="one+count">');
document.write('Lable2');
document.write('<input type="text" name="two+count">');
document.write('Lable3');
document.write('<input type="text" name="three+count">');
document.write('Lable4');
document.write('<input type="text" name="four+count">');
document.write(count);
}
</script>
</body>
</html>

Categories

Resources