add element with DOM model before paragraph - javascript

I want add new input text before paragraph. But it working opposite add after text.
What is wrong at this code?
I use document.getElementById("p1").insertBefore(node); with this aim, but without success. Why does this happen?
Code:
<html>
<head>
<title>Adding text to a page</title>
<script>
function addText() {
var sentence=document.form1.sentence.value;
var node=document.createTextNode(sentence + " ");
document.getElementById("p1").insertBefore(node);
}
</script>
</head>
<body>
<h1>Create Your Own Content</h1>
<p id="p1">Using the W3C DOM, you can dynamically
add sentences to this paragraph. Type a sentence
and click the Add button.</p>
<form name="form1">
<input type="text" name="sentence" size="65">
<input type="button" value="Add" onClick="addText();">
</form>
</body>
</html>
Question:
How to solve this issue?

The insertBefore method needs to be called on the parent node (in which you want to insert), just like appendChild:
var node=document.createTextNode(sentence + " ");
var p1 = document.getElementById("p1");
p1.parentNode.insertBefore(node, p1);
If you want to add sentences to the paragraph instead of before it (right into the <body>), you would use this:
p1.appendChild(node); // insert at the end
// or
p1.insertBefore(node, p1.firstChild); // insert at the beginning

You could
Grab the new sentence.
Grab the original content.
Put them both together in a variable.
Clear the element.
Slap it back in.
Like so:
var addText = function() {
var sentence = document.form1.sentence.value;
var node = document.createTextNode(sentence + " ");
var el = document.getElementById("p1");
var original = el.innerHTML;
var newPara = sentence + ". " + original;
el.innerHTML = "";
el.innerHTML = newPara;
}
jsFiddle
Mind you, this is alot of steps, but hey, a million ways to skin a cat.
Of course you could always shorten all of that code up there to this:
var addText = function() {
document.getElementById("p1").innerHTML = document.form1.sentence.value + ". " + document.getElementById("p1").innerHTML;
}
new jsFiddle

Related

Insert value at position X

Hello I would like to add HTML on to a page once it finds particular text. I have managed to get the position I just can figure out how to add text
$(document).ready(function () {
var position = document.documentElement.innerHTML.indexOf('Gas');
//insert HTML at position
})
So since you already know where to insert, just do
var str = element.innerHtml;
element.innerHTML = str.substr(0, position - 1) + "<b>My HTML</b>" + str.substr(position);
Other way it would be to wrap that text in some element and do .insertBefore()
$(document).ready(function () {
var text = $('.my-text').html();
$('.my-text').html(text.replace(/Gas/, '<span id="my-unique-id">Gas</span>'));
var htmlToInsert = $('<b>', {text: 'Inserted text'});
htmlToInsert.insertBefore('#my-unique-id');
$('#my-unique-id').unwrap();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-text">
Abc def Gas Mesa Bas Ras
</div>

How to Create a counter Loop that starts when submit button is clicked and outputs multiple lines of words with a number in front of each word?

I need to create a counter loop that begins after the user clicks the "submit" button. However, this "submit" button is already being used in another variable. The submit button needs to do two things here, at the same time, and I cannot figure out how to make that work. When the user inputs their information for their first name, last name, and middle initial, and then clicks the submit button, not only will the header change, but a counter to 125 needs to begin. Here is my code so far. What changes do I need to make sure that when the user clicks submit, the <h1> changes with their name in the greeting, and a loop begins counting from 1 to 125 with words like "hello world" after it.
example:
1)Hello World
2)Hello World
3)Hello World
etc
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="fizzbuzz.css">
<title>Fizz Buzz 0</title>
<script>
function clickFunction(){
var firstName = document.getElementById("firstName").value;
var middleName= document.getElementById("middleName").value;
var lastName= document.getElementById("lastName").value;
document.getElementById("greeting").innerHTML =
"Welcome, " + firstName + " " + middleName+ " " +lastName + "!";
};
function clickFunction = ""; {
while (var i=0;i<125;i++) {
out = out + "London Kings" + "</br>";
document.getElementById("greeting").innerHTML = out;
}
}
</script>
</head>
<body>
<div id="header">
<p>
<img src="images/banner.jpg" alt="Banner" height="130" width="940" style="border:0" />
</p>
</div>
<div id="content">
<div id="feature">
<h2 id="greeting"> Welcome to London Kings Football! </h2>
<form>
First Name <input id="firstName"> </input>
Middle Initial <input id="middleName"> </input>
Last Name <input id="lastName"> </input>
</form>
<button onClick="clickFunction()",> Submit </button>
</div>
</div>
</body>
</html>
Some changes you can make to make to your current code so it runs
change the while loop to a for loop
initialize the out variable ( you are using it before it is defined
in a right hand assignmen)
So you final function is
function clickFunction() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var lastName = document.getElementById("lastName").value;
var out = '';
document.getElementById("greeting").innerHTML = "Welcome, " + firstName + " " + middleName + " " + lastName + "!";
for (var i = 0; i < 125; i++) {
out = out + "London Kings" + "</br>";
document.getElementById("greeting").innerHTML = out;
}
}
Other things that could make your code better
Dont add the event listener inline, its harder to reason for your code
instead use document.querySelector("button").addEventListener("click", function(){});
move your script tag just before the closing body tag (</body>) this way the javascript code parsing will not block the rendering of the page (js runs in one thread)
dont query the DOM for each repetition of the for loop instead move the greeting query to the top of the function so you run it only once (per function call)
dont query for the DOM elements each time you run the code(better solution to 3 above, instead either move queries to the top level (those vars will be global, we dont like globals) or create a closure which will encapsulate your valiables
#4 example
var clickFunction = (function(){
var firstName = document.getElementById("firstName");
var middleName = document.getElementById("middleName");
var lastName = document.getElementById("lastName");
var greeting = document.getElementById("greeting");
var out = '';
return function(){
greeting.innerHTML = "Welcome, " + firstName + " " + middleName + " " + lastName + "!";
for (var i = 0; i < 125; i++) {
out = out + "London Kings" + "</br>";
greeting.innerHTML = out;
}
}
}())
document.querySelector("button").addEventListener("click", clickFunction)
script tag containing the above code has to be before the closing body tag

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

JavaScript string replace in textarea

I'm trying to create a simple page that "corrects" YouTube's old embed code so that it works in PowerPoint 2010. If I hard code the embed code into a textarea on the page, it works fine, but if the user pastes the embed code into the text area, the javaScript doesn't seem to run.
Take a look here:http://jsfiddle.net/pch8N/
Here's what I have so far:
<p>Click the button to "fix" the old embed code</p>
<textarea rows="10" cols="60" id="demo"></textarea>
<br/>
<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML;
var n=str.replace(/\/\/www.youtube/g,"http://www.youtube").replace(/version=3/g,"version=2");
document.getElementById("demo").innerHTML=n;
}
</script>
<button onclick="myFunction()">Try it</button>
Thanks for the help!
You should use value instead of innerHtml
function myFunction2()
{
var str=document.getElementById("demo2").value;
var n=str.replace(/\/\/www.youtube/g,"http://www.youtube").replace(/version=3/g,"version=2");
document.getElementById("demo2").value=n;
}
var str=document.getElementById("demo").innerHTML;
You should use .value and not .innerHTML
Put your textarea inside form tag
Then use
var str=document.getElementById("demo").value;
// hope this would be usefull
// i used these codes for auto completing the texts in textarea.
// other methods change all matching items before the selected text
// but this affects only the text where caret on.
// at first, i divided textarea.value into 3 pieces. these are ;
// p1; until the 'searched' item, p2 after 'searched' item
// and pa = new item that will replaced with 'searched' item
// then, i combined them together again.
var tea = document.getElementById(targetTextArea);
caretPosition = tea.selectionStart - ara.length; //ara=searched item
p1 = tea.value.substring(0,caretPosition);
console.log('p1 text : ' + p1);
p2 = tea.value.substring(caretPosition+ara.length,tea.value.length);
console.log('p2 text : ' + p2);
pa = yeni; //new item
console.log('pa text : ' + pa);
tea.value = p1 + pa + p2;
tea.selectionStart = caretPosition + yeni.length;
tea.selectionEnd = caretPosition + yeni.length;
tea.focus();

Add line break to HTML from Js loop

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \n escape character, but it didn't do anything. Any help would be appreciated.
function generateIDs()
{
var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;
}
<form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>
<p id="numbers">
</p>
\n doesn't mean much to a browser; use <br/> instead.
Example:
// snip
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id.toString() + '<br/>';
}
//snip
Note that this is going to overwrite the previous value on each iteration. You probably want this:
par.innerHTML += id.toString() + '<br/>';

Categories

Resources