Appending HTML inputs using JavaScript gives "undefined" value - javascript

I have a small code trying to append values using HTML inputs to the same document.
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
<script type="text/javascript">
var child = document.getElementById("text").value;
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para' + toString(child) + '</p>');
}
</script>
the variable child dose not take the text value from the input, which outputted as `undefined'
image 1: typed Test
Image 2: Clicked the Button
how to get the value form the input as New ParaTest?
Code Edited using the answer.

You don't need toString() method, remove it.
Get the reference of element in the child variable and get the value the func()
var child = document.getElementById("text");
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para: ' + child.value + '</p>');
}
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>

child variable needs to assign inside func function and don't need toString()
try this
function func(){
var h = document.getElementById('myh');
let child = document.getElementById("text").value;
h.insertAdjacentHTML('afterend','<p> New Para' + child + '</p>');
}
<html>
<body>
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
</body>
</html>

Your variable should be global. Try taking it inside the function and then check it.
function func(){
var child = document.getElementById("text").value;
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend','<p> New Para' + toString(child) + '</p>');
}

Related

How do I change from an alert message to a regular text output?

I have a code snippet of my function that will output the total calculated GPA which is:
alert("GPA = " + eval(gpa));
However, I do not want it outputted as an alert.
I want it outputted in regular text.
So how do I change that so in HTML it will just output it in regular text instead of an alert ?
Is there a way to just replace the
alert
part of the code with something else ?
First create a div where you want to show text
<div class="text-message" style="display:none;"></div>
And change alert message with
$(".text-message").text("GPA = " + eval(gpa)).show();
OR to animate it
$(".text-message").text("GPA = " + eval(gpa)).fadein();
You could try something like following with HTML + JavaScript.
function gpa(param1 = 1, param2 = 2){
let resultGPA = param1 + param2;
console.log("GPA = " + resultGPA);
document.getElementById('evalElement').innerHTML = resultGPA;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button name="btn" onclick='gpa()'>Calculate GPA</button>
<p id = "evalElement"></p>
</body>
</html>
This should help you achieve your goal!
If your html element id is gpa, then in your JavaScript-file use following:
document.getElementById("gpa").innerHTML = "GPA = " + eval(gpa);
Step 1
Let's change your alert code to:
myAlert("GPA = " + eval(gpa));
Step 2
Implement myAlert
function myAlert(content) {
let context = document.getElementById('message-block');
context.display = 'block';
context.querySelector('.content').innerHTML = content;
}
Step 3
Create the structure:
<div id="message-block" style='display: none;'>
<div class="content"></div>
<input type="button" value="Close" onclick="this.parentNode.display = 'none';"
</div>
let gpa = "'a'+'b'";
function myAlert(content) {
let context = document.getElementById('message-block');
context.style.display = 'block';
context.querySelector('.content').innerHTML = content;
}
myAlert("GPA = " + eval(gpa));
<div id="message-block" style='display: none;'>
<div class="content"></div>
<input type="button" value="Close" onclick="this.parentNode.style.display = 'none';">
</div>

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

Insert new code to page using JS, with variables

I need to choose values in three text forms (a,b,c), for ex. 1,2,3. Then click ADD, and it will insert code like this:
<mycode a="1" b="2"><newone c="3"></newone></mycode>
How can I do it? For a while trying different approaches.
Using this code I can add new element to the page
<p> <span id="mytext">click here</span></p>
<script type="text/javascript">
function EditText() {
document.getElementById('mytext').innerHTML = '<mycode a="1" b="2"><newone c="3"></newone></mycode>';
}
</script>
But how can I edit a, b and c values using text-form?
Thank you very much!
Assuming you would also like to be able to pass the values for a, b and c to the function and output them in the newly created DOM. You could do something like the following:
function EditText(aVal, bVal, cVal) {
document.getElementById('mytext').innerHTML = '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
Appending additional elements each click:
function EditText(aVal, bVal, cVal) {
var currentInnerHtml = document.getElementById('mytext').innerHTML;
document.getElementById('mytext').innerHTML = currentInnerHtml + '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
If you have three textareas on the screen, you can get their values using JavaScript and then add them in your string instead of hardcoding them.
<textarea id="textA" cols="30" rows="10"></textarea>
<textarea id="textB" cols="30" rows="10"></textarea>
<textarea id="textC" cols="30" rows="10"></textarea>
<p> <span id="mytext">click here</span></p>
<script>
function EditText() {
var textA = document.getElementById('textA').value;
var textB = document.getElementById('textB').value;
var textC = document.getElementById('textC').value;
document.getElementById('mytext').innerHTML = '<mycode a="' + textA + '" b="' + textB + '"><newone c="' + textC + '"></newone></mycode>';
}
</script>

Why do I get a type error when trying to access the value of an element stored in a variable?

I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.

pass a html text in an input field using HTML DOM by innerHTML

I have a problem in geting the html content from a div am pass it into an input field
I'm using the following code:
<html>
<body>
<div id="void">
<div id="main"><strong>Hello</strong> my friend</div>
</div>
<br>
<input type="text" id="resul" >
<br>
<script type="text/javascript">
x=document.getElementById("void").getElementsByTagName("div");
document.write("Text of first paragraph: " + x[0].innerHTML);
document.getElementById("resul").value=x[0].innerHTML;
</script>
</body>
</html>
If you will try it, you will see what I mean. By using the command document.write() I get the value that I need from de div tag : "Hello my friend" but when I want to pass this value "Hello my friend" into an input field I get something like this "Hello my friend".
How can I pass into the input field only the text "Hello friend" without tag.
Any help would be much appreciated! Thanks!
How about this:
<script type="text/javascript">
var x = document.getElementById("main");
document.write("Text of first paragraph: " + x.innerHTML);
document.getElementById("resul").value= x.innerHTML;
</script>
to pass the content without the tag you can use
x.textContent || x.innerText;
so:
var x = document.getElementById("main");
var text = x.textContent || x.innerText;
document.write("Text of first paragraph: " + text);
document.getElementById("resul").value = text;

Categories