display data in blank array javascript. <div> - javascript

So far I have been able to come up with something like this. And i have been able to send something to an array, but in the display, thats what i have not been able to achieve so far.
Hence i am asking, How do i display it?
<!doctype html>
<html>
<head>
<script type=text/javascript>
var array = [];
function add_element_to_array() {
array.push(document.getElementById("institution_name").value);
array.push(document.getElementById("degree_obtained").value);
array.push(document.getElementById("honors_acheieved").value);
document.getElementById("institution_name").value = "";
document.getElementById("degree_obtained").value = "";
document.getElementById("honors_acheieved").value = "";
}
function display_array()
{
// Display array
}
</script>
</head>
<title>Test Javascript</title>
<h1>Test JS</h1>
<body>
<form name="xform" id="xform" method="post" action="samris.php" /> Institution Name:
<input type="text" name="institution_name" id="institution_name" /> </br>
Degree Obtained:
<input type="text" name="degree_obtained" id="degree_obtained" />
</br>
Honors Achieved:
<input type="text" name="honors_acheieved" id="honors_acheieved" />
</br>
</p>
<input type="button" name="Add" id="add" value="add" onclick="add_element_to_array()" />
</form>
<div onload= display_array()>
</div>
</body>
</html>

To display array:
function display_array(){
var display = array.join('<br>');
this.innerHTML = display; // only works if you call it inline (except onload).
/* OR */
// works everywhere when you add an id to the div except onload (see explanation below).
document.getElementById('display').innerHTML = display;
}
/* ... in the HTML ... */
<div id="display"></div>
However you will still not able to display it in the div because of the onload=display_array().
When the div is being loaded, display_array() will be called. However when it is being loaded, array is still empty because nothing has been added to it yet by onclick=add_element_to_array().
To do that, you can call display_array() from within add_element_to_array() like so:
function add_element_to_array(){
/*
your code
*/
display_array();
}
Alternatively, you need to remove the onclick and replace by addEventListener in your <script>. However, you will need to move your <script> tag to the bottom of your <body> tag or otherwise implement a function similar to jQuery's ready().

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.

generate textboxes based on number enter by user

I want when a user enter number in the textbox and click set, textboxes appear based on the number he entered and this what I come up with but it is not working please help
<html>
<head>
<script>
function generate(){
var a=parseInt(document.getElementById("nochapter").value);
for (i=0;i<=a,i++){
document.getElementById("ch").innerHTML="<input type='text' >"}}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included <input type="text" id="nochapter" >
<input type ="button" value="set" onclick="generate()">
<div id="ch"></div>
Your code should be like this.
Is better append an input element to the div.
<head>
<script>
function generate() {
var a = parseInt(document.getElementById("nochapter").value);
var ch = document.getElementById("ch");
for (i = 0; i < a; i++) {
var input = document.createElement("input");
ch.appendChild(input);
}
}
</script>
</head>
<body>
<h1> Prepare new assessment</h1>
<form>
No. of Chapter included
<input type="text" id="nochapter" />
<input type="button" value="set" onclick="generate()" />
<div id="ch"></div>
</form>
</body>
There is small glitch in your written code
for (i=0;i<=a,i++) --> for (i=0;i<=a;i++)
even if you change that it will generate only one text box because you are replacing innerHTML for every iteration. so prepare the string separately based on no of iteration and assign it to innerrHTML. it should work.

Javascript code not being executed on button click

I have some html and some javascript code that is supposed to take input in a text box, and open a new tab with the Wikipedia page of whatever was in the text box. However, I'm using this as an extension, and google chrome doesn't allow inline javascript.
page.js
document.getElementById("search").addEventListener("click", searchPage);
function searchPage() {
console.log("test")
var temp = document.getElementById(pageName);
var temp = temp.value;
var myPage = "http://en.wikipedia.org/wiki/" + temp;
window.location.replace(myPage);
}
popup.html
<!DOCTYPE html>
<html>
<body>
Random
Enter page to lookup: <input type="text" id="pageName" /><br />
<input type="submit" value="Submit" id="search" />
<script src="./page.js></script>
</body>
</html>
Anyone have any clue why this isn't working?
what you can do instead is include your JS in your HTML <head> tag, and add an onClick attribute to your button, like so:
<!DOCTYPE html>
<html>
<body>
<a href="http://en.wikipedia.org/wiki/Special:Random/" target="_blank">$
Enter page to lookup: <input type="text" id="pageName" /><br />
<input type="submit" value="Submit" id="search" />
<script src="./page.js"></script>
</body>
</html>
I think the problem was that in your original code, you had <script src="./page.js></script> instead of <script src="./page.js"></script>
then you can change your javascript to be the following:
document.getElementById('search').addEventListener('click', searchPage);
function searchPage() {
console.log("hjabdfs");
var temp = document.getElementById('pageName');
var temp = temp.value;
var myPage = "http://en.wikipedia.org/wiki/" + temp;
window.location.replace(myPage);
}
please note that I also changed var temp = document.getElementById(pageName) to var temp = document.getElementById('pageName'), as pageName is not a variable.
Input type submit is trying to submit a form. You need to add an action to that submit button or you can change it to a button and the event will fire.
Your click event listener doesn't work because it has not been loaded yet. Or in other words, you need to make sure this line <script src="./page.js></script> is correctly pointing to page.js.

innerHTML not displaying text

Please excuse my basic query to javascript and html
I am new to javascript and html. I am trying to work with javascript on click and few other things. In below code, am trying to display a text on "onclick" function. I am using an external javascript.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" >
<script type="text/javascript" src="/home/roger/Documents/html/myScript.js"></script>
</head>
<body>
<form>
First Name: <input type="text" name="first" id="names"/><br>
Phone Number: <input type="number" name="numb" id="numb"/><br>
<button type="button" onclick="verifyText()">Click Me!</button>
</form>
</body>
</html>
Below is my code in myScript.js
function verifyText(){
document.getElementById("names").innerHTML = "Why not displaying?.";
}
If I put alert in function, pop comes out, but I am unable to figure why innerHTML is not working. Any help will be highly appreciated. Thanks.
You need to set the value, because names is an input field.
document.getElementById("names").value = "Why not displaying?.";
See: http://jsfiddle.net/zrmrx/
names is an <input>. You need to set its value, instead of innerHTML. Try this:
function verifyText(){
document.getElementById("names").value = "Must display now!";
}
Use the javascript element.setAttribute('[attr]','string') to save the user input values or input checkbox checks as part of the document innerHTML. The reset() function changes the form input back to its current Attribute setting. Javascript can dynamically change the default input value with the setAttribute therefore, change the user input default value when reset() is clicked or your code reloads it as part of a saved innerHTML.
function update_attribute() {
var obj = document.getElementById('demo');
if (obj.type == 'checkbox') {
if (obj.checked == true) {
obj.setAttribute('checked', 'checked');
} else {
obj.removeAttribute('checked');
}
}
if (obj.type == 'text') {
obj.setAttribute('value', obj.value);
}
}
<form id='myform'>
<label>Text Input</label><br>
<input type='text' id='demo'>
<br>
<br>
<button type='button' onclick='update_attribute(this)'>Change Attribute</button>
<button type='reset'>RESET</button>
</form>

How to create a tree structure in Javascript DOM?

This is going to sound too silly / too basic - sorry about that, but I experimented a lot and couldn't come to the right solution!
I'm using this following piece of code - which makes a row of text fields go up and down. Unfortunately, the up and down movement doesnt stop and carries on throughout the page! :)
function up(row) {
// need to stop somewhere
var prevRow = row.previousSibling;
if(prevRow != null) {
row.parentNode.insertBefore(row, prevRow);
}
};
function down(row) {
// need to stop somewhere as well
var nextRow = row.nextSibling;
row.parentNode.insertBefore(row, nextRow.nextSibling);
};
My generated html is a combination of xml and xsl. The XSL looks like this:
<xsl:for-each select=".../...">
<p>
<button type="button" onclick="up(this.parentNode)">Up</button>
<button type="button" onclick="down(this.parentNode)">Down</button>
<input>
...
...
...
</p>
</xsl:for-each>
As described above, this works, but the up and down movements dont stop. I tried enclosing the xsl:for-each in another p tag, and a div tag, but neither worked. I was trying to have the parent of these p tags as something other than the body tag.
Did I make myself clear?
Generated HTML added below:
<html>
<head>
<script>
function up(row) {
...
};
function down(row) {
...
};
</script>
</head>
<body>
<form name="edit_form" action="edit.php" method="POST">
...
<?xml version="1.0"?>
...
<p>
<button type="button" onclick="up(this.parentNode)">Up</button>
<button type="button" onclick="down(this.parentNode)">Down</button>
<input name="CRorder[record10354881]" type="text" value="0" disabled="" size="4"/>
<input name="CRpreference[record10354881]" type="text" value="10" disabled="" size="4"/>
<input name="CRlabel[record10354881]" type="text" value="label1"/><input name="CRvalue[record10354881]" type="text" value="22222222222"/></p>
<p><button type="button" onclick="up(this.parentNode)">Up</button>
<button type="button" onclick="down(this.parentNode)">Down</button>
<input name="CRorder[record10354882]" type="text" value="1" disabled="" size="4"/>
...
...
</form></body>
</html>
Based on your HTML, and assuming the ...s do not contain matched pairs of tags that will make the P a child, the P containing the Up/Down buttons (and other paraphinalea) will move up the list of Ps until it is the first child of the FORM tag. As this is directly adjacent to the BODY tag, this is, in effect, moving it all the way up the page.
Edit: OK, from your comment, if you have other siblings to the P tags that you don't to move them past, you'll need to mark them somehow and change your up/down functions to obey those limits. Something like...
...<tag id="upperLimit">...
function up(row) {
// need to stop somewhere
var prevRow = row.previousSibling;
if(prevRow != null && prevRow != document.getElementById("upperLimit")) {
row.parentNode.insertBefore(row, prevRow);
}
};
with a similar restriction on the lower limit.

Categories

Resources