Can't put created paragraph element into div? - javascript

So i'm trying to make a simple comments page but I can't seem to get it working :/ Is there something wrong with the code? I'm trying to use only javascript since I have not learned JQuery
function action(){
var input = document.getElementById('header').value;
localStorage.setItem('comment',input);
document.getElementById('header').value=" ";
var getInput = localStorage.getItem('comment');
var date = Date();
var parag = document.createElement('P')
parag.innerText=getInput;
document.getElementById('hello').appendChild=parag;
}
<textarea id='header' type='text' rows='6' cols='100' name='server'>
</textarea>
<input onclick="action();" type="button" value='Comment'>
<span id='hello'></span>

document.getElementById('hello').appendChild=parag;
You are not calling the appendChild function properly. You are assigning instead. You should do
document.getElementById('hello').appendChild(parag);
Note: in below codes I removed the local storage because of security issues.
--
function action(){
var input = document.getElementById('header').value;
//localStorage.setItem('comment',input);
document.getElementById('header').value=" ";
// var getInput = localStorage.getItem('comment');
var date = Date();
var parag = document.createElement('P')
parag.innerText="getInput";
document.getElementById('hello').appendChild(parag);
}
<textarea id='header' type='text' rows='6' cols='100' name='server'>
</textarea>
<input onclick="action();" type="button" value='Comment'>
<span id='hello'></span>

Just change you append child to :
document.getElementById('hello').appendChild(parag);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<script type="text/javascript" charset="utf-8">
function action(){
var input = document.getElementById('header').value;
localStorage.setItem('comment',input);
document.getElementById('header').value=" ";
var getInput = localStorage.getItem('comment');
var parag = document.createElement('P')
parag.innerText=getInput;
document.getElementById('hello').appendChild(parag);
}
</script>
<body>
<textarea id='header' type='text' rows='6' cols='100' name='server'>
</textarea>
<input onclick="action();" type="button" value='Comment'>
<div id='hello'></div>
</body>
</html>

The syntax for Node.appendChild is wrong.
You can see how to use it in the DOM Living Standard.
The appendChild(node) method, when invoked, must return the result of appending node to context object.
You should also consider keeping a reference to header instead of querying the DOM twice.

Related

Why the button object can not use the onclick() function?

I am trying to use javascript to create a web calculator. I hope that users can calculate the result when they click the different buttons. However, there is an error in line16(Uncaught TypeError: Cannot read property 'onclick' of null). I hope someone could help me. These are my codes:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
</style>
<script type="text/javascript">
var btnadd,btnsub,btnmul,btndiv;
btnadd = document.getElementById('btnadd');
btnsub = document.getElementById('btnsub');
btnmul = document.getElementById('btnmul');
btndiv = document.getElementById('btndiv');
btnadd.onclick() = function(){
cal(add());
}
function cal(func){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
parseFloat(num1);
parseFloat(num2);
var result;
result = func(num1,num2);
document.getElementById('result').value = result;
}
function add(num1,num2){
return (num1+num2);
}
function sub(num1,num2){
return (num1-num2);
}
function mul(num1,num2){
return (num1*num2);
}
function div(num1,num2){
return (num1/num2);
}
</script>
</head>
<body>
<form>
num1:<input type="text" id="num1" /><br>
num2:<input type="text" id="num2" /><br>
<input type="button" id="btnadd" value="add" />
<input type="button" id="btnsub" value="sub" />
<input type="button" id="btnmul" value="mul" />
<input type="button" id="btndiv" value="div" /><br>
result:<input type="text" id="result"/>
</form>
</body>
</html>
You need to either add the defer attribute to your script or put it at the end of the body.
Putting JS code in the head means that it will be run before the page is fully parsed. That means that there is no element with the id of btnadd just yet. If you add the defer attribute, then it will wait for the page to be parsed before running the script. Putting at the end of the body has the same effect.
In terms of your code itself, you need to set the onclick property. You cannot assign a function like that. Also, do val2 = parseFloat(val2) rather than parseFloat(val2). (similarly for val1) because here you need to reassign the value
Because you didn't define the onclick correctly
Instead of
btnadd.onclick() = function(){
cal(add());
}
try
btnadd.onclick = function(){
cal(add);
}
Check this codepen : https://codepen.io/zecka/pen/NWrejxO
Note that there are other errors in your code that will prevent you from making it work as you want.

Second exists condition does not work

I'm having a question about javascript where I have two conditions to check if the input fields exists. But it only shows me that "opleiding exists" and not that "opleiding exists" and "domein exists".
please tell me what's wrong with my code.
Thanks very much !
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
if(document.getElementById("opleiding")){
document.write("opleiding exists");
}
if (document.getElementById("domein")){
document.write("domein exists");
}
}
</script>
</head>
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
</html>
document.write will override the existing content in the page. That's the reason why you're seeing only on message.
You must use document.body.appendChild instead to show both error messages.
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
var textElement;
if(document.getElementById("opleiding")){
textElement = document.createElement("p");
textElement.textContent = "opleiding exists";
document.querySelector("#results").appendChild(textElement);
}
if (document.getElementById("domein")){
textElement = document.createElement("p");
textElement.textContent = "domein exists";
document.querySelector("#results").appendChild(textElement);
}
}
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="results"></div>
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
You should avoid using document.write, since that it's a deprecated method. When you use it the first time, it will write down what you want, but remove all the content of the page, as per its definition.
To do what you want you should "write" using either document.body.appendChild to append some element (like a <div>) containing text, or add some text to the document.body.innerHTML, here's an example:
function submit() {
var opleiding_div = document.createElement('div'),
domein_div = document.createElement('div');
opleiding_div.textContent = "opleiding exists";
domein_div.textContent = "domein exists";
if(document.getElementById("opleiding")){
document.body.appendChild(opleiding_div);
}
if (document.getElementById("domein")){
document.body.appendChild(domein_div);
}
}

Array contents would not display

I have created a javascript code that lets the user input something then it should display after the input but my display seems to not work at all, I am using document.getElementById to display the array content per input but it is not working.
Here is my complete code:
<html>
<meta charset="UTF-8">
<head>
<title>Sample Array</title>
<script>var index = 0;</script>
</head>
<body>
<p id = "display">
Input:
<input type="text" id="input">
<input type="button" value="GO" onClick="press(input.value)">
<script>
var sample = new Array();
function press(Number)
{
sample[index] = Number;
document.getElementById("display").InnerHTML += sample[index] + " ";
index++;
}
</script>
</body>
</html>
What seems to be the problem? I am still learning the basics please bear with me.
The problem is with "InnerHTML". The correct syntax is "innerHTML" with small "i".
change
document.getElementById("display").InnerHTML
to
document.getElementById("display").innerHTML
(note the lowercase i
Here's the fiddle
I made two tiny changes that seem to make this work.
First, close the <p> tag so that when you set innerHtml it does not include the inputs.
Second, change InnerHHTML to innerHTML. Methods and properties are case sensitive.
<p id = "display"></p>
Input:
<input type="text" id="input">
<input type="button" value="GO" onClick="press(input.value)">
<script>
var sample = new Array();
function press(Number)
{
sample[index] = Number;
document.getElementById("display").innerHTML += sample[index] + " ";
index++;
}
</script>
First your <p> is not complete;
<p id = "display"></p>
Second its:
document.getElementById("display").innerHTML += sample[index] + " ";

document.write(); removes other HTML [duplicate]

This question already has answers here:
Why is document.write considered a "bad practice"?
(17 answers)
Closed 9 years ago.
I'm doing a test for a comment thing. All I want is to have a little text box where you type stuff and a button that says "Add Comment" that will document.write(); what you put in the text box under the add comment thing. But I'm getting a problem where document.write(); seems to be removing all the other HTML that was written out side the javascript (i.e. the textarea and the "Add Comment" button). When I press the "Add Comment" button, what I wrote in the textarea fills up the whole screen and seems to be blotching out the rest. Here is my code:
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p>Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
document.writeln(input);
}
</script>
</body>
</html>
You can not use document.write once the document has completed loading. If you do that then browser will open a new document and it will replace it with the current. So it is the design behavior of document.write
It would be better to use innerHTML to put HTML inside element
Try like this:
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>
Also check Why is document.write considered a “bad practice”?
Well instead of using document write, you should append or fill into targeted element, I modified your code a little bit, It might help you.
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>
If you wanna append only from original document, you can use it as
test.innerHTML = test.innerHTML + input;
Furthermore
How to append data to div using javascript?
Don't use document.write().Instead use innerHTML
Note:Your code will not work as you are using tf.value where tf is object of textarea which don't have value attribute. So I recommend to use innerHTML.
<html>
<script language="JavaScript">
<head>
function add1(){
var tf = document.getElementById('tf');
add2(tf.innerHTML);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>
The other comments are correct: document.write() is not something you want to be using. You'll still see that method suggested in some of the older books on JavaScript, but it's really a terrible way to modify the document, for many reasons I won't get into here.
However, no one's suggesting what you can do instead, so I'll point you in the right direction.
If you want to modify elements in your HTML, your best bet is to use the innerHTML property of DOM objects. For example, let's say you have a <div id="output"> that you want to add text to. You would first get a reference to that DOM element thusly:
var outputDiv = document.getElementById( 'output' );
Then you can either completely change the contents of that <div>:
outputDiv.innerHtml = 'Hello world!';
Or you can append to it:
outputDiv.innerHtml = outputDiv.innerHtml + '<br>Hello world!';
Or even more compactly with the += operator (thanks nplungjan):
outputDiv.innerHtml += '<br>Hello world!';
You should also look at jQuery at some point, which gives you a whole boatload of convenience functions to make these kind of manipulations a snap.
I hope this sets you in the right direciton.

Noob JavaScript Question - trying to assign a variable from a html text input and then have that variable used in a function

I'm trying to assign a variable from a html text input value and then have that variable used in a function that uses the jquery ":contains" selector to hide divs that don't match the variable...here is the code I have...
<head>
<script language="JavaScript" type="Text/JavaScript" src="jquery.js"></script>
<script language="JavaScript" type="Text/JavaScript">
var myform = document.forms[0];
var FilterText = myform.FilterText.value;
function FilterBlocks()
{
$("div.block").hide();
$("div.block:contains(FilterText)").show();
}
</script>
</head>
<body>
<form action="#">
<input class="navButtons" type="text" name="FilterText">
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" onMouseUp="FilterBlocks()">
<br /><br />
</form>
<div class="block"><a href="1.html"><img src="images/1.jpg">This is the title<a></div>
</body>
I tried doing an alert() with the variable that I an trying to use but it's coming back undefined.
Any help would be greatly appreciated...thanks!
Try $("div.block:contains(" + FilterText + ")").show(); instead. You'll need to 'escape' special characters too ((, ), etc), but this should work on simple strings.
And BTW, what you are coding in called Javascript, not Java.
you might want to do it this way,
function FilterBlocks(){
$("div.block").hide();
$("div.block:contains("+FilterText+")").show();
}
and also, calling var myform = document.forms[0];, in your code above, would result myform as undefined because DOM is not yet ready.
you might want it this way,
<script language="JavaScript" type="Text/JavaScript">
$(function(){
// call it when DOM is ready
var myform = document.forms[0];
var FilterText = myform.FilterText.value;
function FilterBlocks(){
$("div.block").hide();
$("div.block:contains("+FilterText+")").show();
}
});
</script>
for better jQuery style codes, I suggest this,
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" onMouseUp="FilterBlocks()">
to just,
<input class="navButtons" type="button" name="FilterButton" value="Filter Videos" >
your jQuery would be,
<script language="JavaScript" type="Text/JavaScript">
$(function(){
// call it when DOM is ready
var myform = document.forms[0];
$('.navButtons:button').click(function(){
var FilterText = myform.FilterText.value;
$("div.block").hide();
$("div.block:contains("+FilterText+")").show();
});
});
</script>

Categories

Resources