Calling a function without clicking anything - javascript

I'm new in programming and I'm trying to call a function without any button or click event. I'm doing a table within a table using javascript function. Here's my code so far:
<html>
<head> <title> Hello </title> </head>
<body>
<table border=1>
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' /> <script> add(); </script> <div id='myDiv'> </div> </td>
</tr>
<script>
$ctra = 1;
$ctr1a = 1;
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1>"+
"<tr>"+
"<td> Hello! <input type='hidden' value='0' id='theValue' /> <script> add(); </script> <div id=('" + divIdName + "')> </div> </td>"+
"</tr>"+
"</table>";
if($ctra<100){
ni.appendChild(newdiv);
$ctra++;
}
}
</script>
</table>
</body>
</html>
When I run it, it displays
"+ ""+ "
Hello!
"; if($ctra<100){ ni.appendChild(newdiv); $ctra++; } }
in the browser. What could the problem be? Thank you in advance!
EDIT
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value=0 id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
for(var i=1;i<100;i++) {
var ni = document.getElementById(divIdName);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='" + i + "' id='theValue' /><div id='" + divIdName + "'></td></tr></table>";
ni.appendChild(newdiv);
}
}

Try this
<html>
<head> <title> Hello </title> </head>
<script type="text/javascript">
$ctra = 1;
$ctr1a = 1;
function add() {
alert('s')
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table border=1><tr><td> Hello! <input type='hidden' value='0' id='theValue' /></tr></table>";
if($ctra<100){
ni.appendChild(newdiv);
$ctra++;
}
}
</script>
<body onload="add()">
<table border="1">
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' />
<div id='myDiv'> </div> </td>
</tr>
</table>
</body>
</html>
Hope it works for you..:)

Your JS results in nested blocks, this isn't allowed in html. The function add() in your blocks is not defined, because when the browser encounters it, it hasn't seen your definition of add() yet. Your table contains a script that contains another table which contains yet another script. It's very confusing :P
OK, if i understand correctly: you have a single table. You'd like to have JS put another table inside. The thing you want to put inside is, in this example, a copy of the table. You want to end up with a table inside a table and you want to achieve it programatically.
First separate your concerns: scripts and html:
If you put your add() after the definition and you put your script after the body then the browser will encounter it and run it. HTH:
<html>
<head> <title> Hello </title> </head>
<body>
<table id="t1" border=1>
<tr>
<td> Hello! <input type='hidden' value='0' id='theValue' />
<div id='myDiv'></div>
</td>
</tr>
</table>
<script>
function add_table() {
var table1 = document.getElementById("t1"),
table2 = table1.cloneNode(true),
mydiv = document.getElementById("myDiv"),
mydiv2;
table2.setAttribute('id', 't2');
mydiv2 = table2.getElementsByTagName("div")[0];
mydiv2.setAttribute('id', 'myDiv2');
mydiv.appendChild(table2);
}
// call the function
add_table();
</script>
</body>
</html>

You have </script> inside the code. Browser interprets that as an end of javascript and breaks back to HTML. To fix this, you can divide this string into for example </sc'+'ript>. That will fix this issue, but probably you'll still have to work a bit on the script, but that's a different story.

You have to switch between differents quotes, and remove braces for the id, like this :
newdiv.innerHTML = "<table border=1>"
+"<tr>"
+'<td> Hello! <input type="hidden" value="0" id="theValue" /> '
+'<script> add(); </script> <div id="' + divIdName + '"> </div> </td>'
+"</tr>"
+"</table>";

Because you cant access the function without any evnt in the dom..You have to call the function on any event of the elemnt.

move the script outside the table-element to the head or to the end of the body.
first add the div, then call the script. you might want to call your add() in <body onload='add'>
remove the braces here to create valid html: <div id=('" + divIdName + "')>

Related

Using input value with onkeyup to innerHTML a div

i have been watching some questions here about the same topic but i cant make my code works with the solutions,
I have a dynamic tr table, what i want to do is when i write on the last input of each row a div "result" overwrite like the values, that because i want to make later a connection that shows me users name on my db, like a data live search
JS
function createTable() {
var a;
var r;
a = document.getElementById('tb1').value;
var length = document.getElementById('table').rows.length;
if (a == "") {
alert("Please enter some numeric value");
} else {
var change = document.getElementById("trow1").style.visibility = 'visible';
//var change = document.getElementById("trow2").style.visibility = 'visible';
var changet = document.getElementById("table").style.visibility = 'visible';
var rows = "";
for (var i = 0; i < a; i++) {
r=i+length;
let tr = document.createElement("tr");
tr.innerHTML = "<td>"+r+"</td><td><input type='text' id='" + "parameter".concat(r) + "'></td><td id='tdlmin'><input type='text' id='" + "lmin".concat(r) + "'></td><td id='tdlmax'><input type='text' id='" + "lmax".concat(r) + "'></td><td><input type='text' id='" + "level".concat(r) + "'></td><td><select id='" + "relcal".concat(r) + "' style='width:100%;'><option value='NA'>NA</option><option value='SI'>SI</option></select></td><td><input type='text' id='" + "comment".concat(r) + "' cols=100></td><td><input type='text' id='" + "procown".concat(r) + "' onkeyUp='document.getElementById('result').innerHTML = this.value;'></div></td>";
document.getElementById("table").appendChild(tr);
}
}
}
HTML
<div class="container-fluid">
<div class="row align-items-start">
<div class="col-9">
Numero de Parametros: <input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Crear</button>
<table id="table" class="order-table table" name="table1" required style="visibility:hidden;">
<tr id="trow1" style="visibility:hidden; text-align: center;"><td>#</td><td>Parametro</td><td colspan="2"><table><tr><td colspan="2">Limite</td></tr><tr><td>Min.</td><td>Max.</td></tr></table></td><td><table style="width: 100%;"><tr><td>Nivel</td></tr><tr><td>1 - 4</td></tr></table></td><td>Relevante Calidad</td><td>Comentario</td><td>DueƱo del Proceso</td></tr>
</table>
<button type="button" onclick='subir()'>Subir Parametros</button>
</div>
<div class="col-3">
<div id="result" name="result"></div>
</div>
</div>
</div>
Edit:
This is what i have tried yet:
$('"'+procownid+'"').on("keyup",function(){
var userlike = document.getElementById(procownid).value;
alert(userlike);
});
$("#table tr").on('keyup', procownid, function({
var userlike = document.getElementById(procownid).value;
alert(userlike);
result.innerHTML="<p>"+userlike+"</p>"
});
alert(userlike);
document.getElementById('result').innerHTML="<p>userlike:"+uselike+"</p>";
$.post('getUser',{accion:"ListarUserTPMD",userlike:userlike}, function(data){
result.innerHTML=data;
});
my question is, i can get that when i write on the input it trigger the onkeyup and show me for example the input.value, why i cant make it write on the div?

Editable table not working

I made a table that you can add text to and edit it inside it.
However if you add more than three rows, It is stuck and not working anymore.
The errors comes from here:
document.getElementById('vda' + z).addEventListener('click', doSomething);
document.getElementById('cvda' + z).addEventListener('click', doSomething2);
It is only adding event listener to the last row added, so if you add more than one row. The not last row won't have a working edit button.
I checked the IDs by inspecting the edit and update buttons elements.
Try adding 3 rows then click on the edit button for one of the row.
you can look at the code here and also https://jsfiddle.net/3e6d4qsv/
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div style="display:inline-flex;">
<form id="myForm">
<input id="inptext" type="text" placeholder="Your name..."></input>
<input id="inpadress" style="margin-left: 10px;" type="text" placeholder="Your email..."></input>
</form>
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button>
</div>
<br>
<div style="display: inline-flex">
<table id="tablename" style="width:80%; margin-top:15px;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</table>
<div id="buttons" style="float:right;width: 300px; margin-top:50px;">
</div>
</div>
<script>
var z = 1;
function myFunction() {
var x = document.getElementById("inptext").value;
var y = document.getElementById("inpadress").value;
var form = document.getElementById("myForm");
form.reset();
document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td id=acvda'+ z + '>' + x + '</td><td id=zcvda' + z + '>' + y + '</td></tr>';
var h = '<button style="margin-left:8px" class="edit" id=vda' + z + '>Edit</button>';
var f = '<div id=zzza'+z+' style=height:10px></div>';
var abc = '<button style="margin-left:-36px" class="update" id="cvda'+z+'">Update</button>';
var total = h + abc + f;
document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + total;
document.getElementById('vda' + z).addEventListener('click', doSomething);
document.getElementById('cvda' + z).addEventListener('click', doSomething2);
document.getElementById('cvda' + z).style.visibility='hidden';
z = z + 1;
}
function doSomething() {
document.getElementById("inptext").value = document.getElementById("ac"+this.id).innerHTML;
document.getElementById("inpadress").value = document.getElementById("zc"+this.id).innerHTML;
document.getElementById(this.id).style.visibility='hidden';
document.getElementById('c'+this.id).style.visibility='visible';
}
function doSomething2() {
document.getElementById("a"+this.id).innerHTML = document.getElementById("inptext").value;
document.getElementById("z"+this.id).innerHTML = document.getElementById("inpadress").value;
document.getElementById(this.id).style.visibility='hidden';
form.reset();
var edit = this.id;
var edit2 = edit.replace("c", "");
document.getElementById(edit2).style.visibility='visible';
}
</script>
</body>
</html>
The following line remove all your listeners:
document.getElementById("buttons").innerHTML =
document.getElementById("buttons").innerHTML + total;
document.getElementById('vda' + z).addEventListener('click',
doSomething);
use this instead:
var div = document.createElement('div');
div.innerHTML = total;
document.getElementById("buttons").appendChild(div);

Getting Input inside <tr> tag within a tbody?

I know this has come up a lot of times and I have searched all over stack overflow. I have created a working Javascript function to get the <input> tag values within each row of a table.
However, when I include a <tbody> tag (which is required for row sorting), the Javascript code will not work and I have no idea why?
Please see the code below:
function writeXML() {
var table = document.getElementById('table_assoc');
alert(table);
var rCount = document.getElementById('tbody_id').rows.length;
alert(rCount);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = "c:/XML.xml";
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<Seating_Plan>\n');
for (var i = 1; i < rCount; i++) {
var id = table.rows[i].cells[0].children[0].value; <-- Cant Find Table reference when <tbody> tag included.
var deptcode = table.rows[i].cells[1].children[0].value;
var name = table.rows[i].cells[2].children[0].value;
var role = table.rows[i].cells[3].children[0].value;
var desc = table.rows[i].cells[4].children[0].value;
var image = table.rows[i].cells[5].children[0].value;
var asdir = table.rows[i].cells[6].children[0].value;
file.WriteLine('<Person id="' + id + '"><Dept>' + deptcode + '</Dept><Name>' + name + '</Name><Description>' + desc + '</Description><Role>' + role + '</Role><Image><image href="' + image + '"/></Image><AssociateDir><AssociateDir href="' + asdir + '"/></AssociateDir></Person>');
}
file.WriteLine('</Seating_Plan>');
file.Close();
}
How do I get this to work when including a tbody tag?
==================================================================
UPDATE:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="Admin_Javascript.js"></script>
</head>
<body>
<div id="Header_Logo" ></div>
<div id="Header_Logo2">BMW UK</div>
<div id="Admin_Header">BMW LAYOUT EDITOR</div>
<div id="Admin_Nav">
<a id="btn_xml" class="Admin_Nav_Buttons">XML</a>
<a class="Admin_Nav_Buttons">Layout</a>
</div>
<div id="Admin_XML">
<div id="XML_Buttons2">LOAD</div>
<div id="XML_Buttons" onClick="writeXML()">SAVE</div>
<span> </span>
<p class="Admin_headers">Departments</p>
<div id="Admin_Dept_Container"></div>
<p class="Admin_headers">Associates</p>
<div id="Admin_Associate_Container">
<table id="table_assoc">
<tbody id="tbody_id" >
<tr><td><input value="ID"></td></tr>
<tr><td><input value="deptcode"></td></tr>
<tr><td><input value="name"></td></tr>
<tr><td><input value="role"></td></tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
There is also a collection of tBodies, you can get the one by its index:
var id = table.tBodies[0].rows[i].cells[0].children[0].value;

Function's code displays at top of webpage

I am trying to get my function to display its executed code inside a div or a table.
At the moment the code is executed and displayed at the top of the page. I want it to display on a specific area on my page. how do i do this?
Here is my external scripts code, called "SquareScript.js":
function Display()
{
var a = document.getElementById("value1").value;
var b = document.getElementById("value2").value;
for(var i = 0; i < a; i++)
{
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
}
document.getElementById("Paragraph").innerHTML += "<br>";
for (var r = 0; r < b; r++)
{
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
for(var p = 0; p < a-2; p++)
{
document.getElementById("Paragraph").innerHTML += "&nbsp&nbsp&nbsp";
}
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
document.getElementById("Paragraph").innerHTML += "<br>";
}
for(var i = 0; i < a; i++)
{
document.getElementById("Paragraph").innerHTML += " " +
document.getElementById("myValue").value;
}
}
My code generates a square on the page with the height and width that the user entered, also using the character the user entered.
Here is my main webpages code:
<head>
<link rel = "stylesheet" type = "text/css" href = "Assignment3.css">
<style>
table {background-color:black;color:white; align: center;}
body {background-image: url('squares.png');}
</style>
</head>
<title>Generate A Square</title>
<body>
<p Id="Paragraph"></p>
<div class = "heading">
<h1><img src = "Interested.png" width = 100px height = 100px></img>WELCOME TO BUILD A SQUARE</h1>
</div>
<table align = center>
<tr>
<td>
Please Enter value number 1:&nbsp&nbsp<input type = "text" id = "value1">
</td>
</tr>
<tr>
<td>
Please Enter value number 2:&nbsp&nbsp<input type = "text" id = "value2">
</td>
</tr>
<tr>
<td>
Enter a character for your square's border:&nbsp&nbsp<input type="text" Id="myValue"> </input>
</td>
</tr>
<tr>
<td>
<button onclick="Display()">Display</button>
</td>
</tr>
</table>
<div style = "margin-left: 45%;">
<button><a href = "MainMenu.html">Return To Main Menu</button>
<script src = "SquareScript.js" ></script>
</div>
</body>
as you can see i call my external script inside tags after my table. But it still displays at the top of the page.
What can I do to display my executed script inside the div tag which i put it in?
Thanks for any help or any suggestions!
Your script generates the square and places it inside
<p Id="Paragraph"></p>
To move the square to the div where you have the script tag, move the existing <p Id="Paragraph"></p> below the script tag. the div code will be
<div style = "margin-left: 45%;">
<button><a href = "MainMenu.html">Return To Main Menu</button>
<script src = "SquareScript.js" ></script>
<p Id="Paragraph"></p> <!-- move this p tag here -->
</div>

JavaScript Renaming Form Image Input Name

I am developing this for use in Internet Explorer 8 (because at work we have to use it). I have a page that has a table withing a form. The table has a button to "clone" rows, "AddScheduleRow()". That part works good. Each row has a button to delete that row "DeleteRow(r)". That part works well too. I also have a script to rename/renumber each row, "RenumberRows()". It almost works good. I can rename the text fields (for example what was previously StartDate3 now becomes StartDate2). However, in each row is an input that is type="image" and it is named like you should with any input. The name of it is "StartDateCal". The problem is that during the renaming process, when it hits the image input (TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;), I get a JavaScript error "'TheForm.StartDateCal' is null or not an object". I cannot figure this one out and it's standing in the way of moving on.
What can I do to try to rename an < input type = image /> ?
Below is the necessary code:
HTML
<html>
<head>
</head>
<body>
<form name="UpdateSchedule" method="post" action="DoSchedule.asp">
<input type="hidden" name="NumRows" value="0">
<input type="hidden" name="RowsAdded" value="0">
<table id="ClassScheduleTable">
<tr id="ScheduleRow" style="display:none;">
<td>
<input type="text" name="RowNum" value="0" size="1" onclick="alert(this.name)">
</td>
<td>
<b>Start Date</b> <input type="text" name="StartDate" value="" onclick="alert(this.name);" size="8">
<input type="image" name="StartDateCal" src="http://www.CumminsNorthwest.com/ATT/Img/Calendar3.png" style="border-style:none;" onClick="alert('name = ' + this.name);return false;">
</td>
<td>
<input type="button" value="Del." name="DelRow" class="subbuttonb" onclick="DeleteRow(this);">
</td>
</tr>
<tr>
<td colspan="3" style="text-align:right">
<input type="button" value="Add Class Date" class="SubButton" onclick="AddScheduleRow();">
</td>
</tr>
</table>
</form>
</body>
<script language="JavaScript">
JS
var TheForm = document.forms.UpdateSchedule;
var NumRows =0;
var RowsAdded =0;
function AddScheduleRow(){
NumRows++;
TheForm.NumRows.value = NumRows;
RowsAdded++;
TheForm.RowsAdded.value = RowsAdded;
var TableRowId = "ScheduleRow";
var RowToClone = document.getElementById(TableRowId);
var NewTableRow = RowToClone.cloneNode(true);
NewTableRow.id = TableRowId + NumRows ;
NewTableRow.style.display = "table-row";
var NewField = NewTableRow.children;
for (var i=0;i<NewField.length;i++){
var TheInputFields = NewField[i].children;
for (var x=0;x<TheInputFields.length;x++){
var InputName = TheInputFields[x].name;
if (InputName){
TheInputFields[x].name = InputName + NumRows;
//alert(TheInputFields[x].name);
}
var InputId = TheInputFields[x].id;
if (InputId){
TheInputFields[x].id = InputId + NumRows;
//alert(TheInputFields[x].id);
}
}
}
var insertHere = document.getElementById(TableRowId);
insertHere.parentNode.insertBefore(NewTableRow,insertHere);
RenumberRows();
}
AddScheduleRow();
function DeleteRow(r){
var i=r.parentNode.parentNode.rowIndex;
document.getElementById("ClassScheduleTable").deleteRow(i);
NumRows--;
TheForm.NumRows.value = NumRows;
RenumberRows();
}
function RenumberRows(){
var TempCounter = 0;
for (var i=0;i<=RowsAdded;i++){
if (TheForm.RowNum[i]){
TempCounter++;
TheForm.RowNum[i].name = "RowNum" + TempCounter;
TheForm.RowNum[i].value = TempCounter;
TheForm.StartDate[i].name = "StartDate" + TempCounter;
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
}
}
}
</script>
</html>
might be to do with your DTD,
try HTML4 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
You can use
document.getElementsByName('StartDateCal')[i].name = "StartDateCal" + TempCounter;
instead of
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;

Categories