javascript addressbook in html table [duplicate] - javascript

This question already has answers here:
Document.write clears page
(6 answers)
Closed 9 years ago.
I tried to make a JavaScript address book and wanted to show it in html table, but it doesn't work. The meaning is: if i click on add contact button, i can fill data in the prompt box. after that i see the result in the table, but instead of that..there is no table! and i can't add a new contact. How can i solve this problem?
JavaScript code:
function addcontact(){
contactName = {
firstName: prompt("firstname",''),
lastName: prompt("lastname",''),
address: prompt("address",''),
phoneNumber: prompt("phonenumber",'')
};
var contact = [contactName];
function printPerson(person){
document.write(person.firstName+"<br />"+person.lastName+"<br />"+person.address+"<br />"+person.phoneNumber+"<br />");
}
function list(){
var contactLength = contact.length;
for(i=0; i < contactLength; i++){
printPerson(contact[i])
}
}
list();
};
and here my html:
<!DOCTYPE html>
<html>
<head>
<title>div insteller</title>
<meta charset="utf-8">
<style type="text/css">
#adsressbook{width:300px;}
#adsressbook td, th{ border:1px solid #000; padding:5px 10px;}
</style>
</head>
<body>
<form action='' method=''>
<table id="adsressbook">
<tr>
<th>Contacten</th>
</tr>
<tr>
<td><script type="text/javascript" src="adress/adres.js"></script></td>
</tr>
<tr>
<td><input type="submit" value="add contact" onclick="addcontact()"></td>
</tr>
</table>
</form>
</body>
</html>

Try something along the following lines:
var contacts = [];
function addcontact() {
var person = {
firstName: prompt("firstname", ""),
lastName: prompt("lastname", ""),
address: prompt("address", ""),
phoneNumber: prompt("phonenumber", "")
};
contacts.push( person );
}
function resetView() {
document.getElementById("output").innerHTML = "";
}
function printPerson( person ) {
document.getElementById("output").innerHTML +=
person.firstName + " - " +
person.lastName + " - " +
person.address + " - " +
person.phoneNumber + "<br />";
}
function listContacts() {
resetView();
var len = contacts.length;
for (x = 0; x < len; x++) {
printPerson( contacts[x] );
}
}
Here's a JSFiddle of it working: http://jsfiddle.net/nttk6/42/
It would probably be better to change printPerson() and resetView() to use the DOM rather then .innerHTML. You can also recombine the functions into 1 function again if you prefer.
The main thing is to move the contact or in my example the contacts variable out of the addContact function otherwise it is reset each time the function is called. Also you don't want to be using Document.Write().
And here's another example of it implemented as a class:
var ContactManager = {
contacts: [],
resetView: null,
appendView: null,
addContact: function(){
var person = {
firstName: prompt("firstname", ""),
lastName: prompt("lastname", ""),
address: prompt("address", ""),
phoneNumber: prompt("phonenumber", "")
};
this.contacts.push( person );
this.listContacts();
},
listContacts: function(){
var len = this.contacts.length;
this.resetView();
for( x = 0; x < len; x++ ) {
this.appendView( this.contacts[x] );
}
}
};
ContactManager.resetView = function(){
document.getElementById("output").innerHTML = "";
};
ContactManager.appendView = function( person ){
document.getElementById("output").innerHTML +=
person.firstName + " - " +
person.lastName + " - " +
person.address + " - " +
person.phoneNumber + "<br />";
};
And the JSFiddle for the class version: http://jsfiddle.net/TPxRa/6/

That is because you are using document.write(). That function is overwriting the content of your document and inserting the text you specified. What you want to do is append a row to your table.
You can check out this example (which is written in jQuery; but makes it a lot easier).

Related

Value not increasing in table in while clicked in javascript

I have a table and when I clicked on leftmost column's number like 1,2,3... I want their respective rightmost column 0 to increase like 1,2,3,4,5...(Increase by 1 on every click.)
var ms=document.getElementById('message');
window.onload = build;
var myArray = ["Laurence", "Mike", "John", "Larry", "Kim", "Joanne", "Lisa", "Janet", "Jane"];
var message = document.getElementById('message');
function build() {
var html = "<h1>My Friends Table</h1><table>";
for (var x = 0; x < myArray.length; x++) {
html += '<tr data-row="' + x + '" data-vote="0"><td class="box" >' + (x + 1) + '</td><td>' + myArray[x] + '</td><td>0</td></tr>';
}
html += '</table>';
document.getElementById('output').innerHTML = html;
var elbox = document.querySelectorAll('#output .box');
var a;
var v;
for (var x = 0; x < elbox.length; x++) {
elbox[x].onclick = function () {
console.dir(this);
a = this.closest('[data-row]').getAttribute('data-row');
console.log(myArray[a]);
message.innerHTML = myArray[a] + " is on row #" + a;
v = this.closest('[data-vote]').getAttribute('data-vote');
v++;
console.log(v);
this.parentElement.lastElementChild.innerText=v;
}
}
}
td {
border: 1px solid #ddd;
padding: 10px;
}
<html>
<head>
<title>Complete JavaScript Course</title>
</head>
<body>
<div id="message">Complete JavaScript Course</div>
<div id="output"></div>
</body>
</html>
I have set v++ but why the value of v is not increasing? I am still seeing value as 1. To update the innertext,I have used
this.parentElement.lastElementChild.innerText=v;
Since <tr> is parent of td and i used this.parentElement.lastElementChild.innerText=v; why its just stuck to 1 on every click?Why it is not increasing after one?
Every time you click it is based on data-vote attribute value of the first td of the row.
You do modify the innerText of the right column but after that you should do something like this to modify the data-vote attribute also:
this.parentElement.firstElementChild.dataset.vote=v;

How to display the data in table format which im currently displaying in page via js ?( i already got input from previous page)

want to display my data in table format in javascript
able to display the data which i recieved from my previous page through query string in next page through document.write
<!DOCTYPE html>
<html>
<head>
<title> result </title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs =
document.URL.substring(idx+1,document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
email = unescape(params["email"]);
mobile = unescape(params["mobile"]);
document.write( "firstname = " + firstname + " <br>" );
document.write( "lastname = " + lastname + "<br>" );
document.write( "age = " + age + "<br>" );
document.write( "email-id = " + email + "<br>" );
document.write( "mobile = " + mobile + "<br>");
</body>
display my data inside table

Why unable to push an object into array through instantiating constructor method? [duplicate]

This question already has answers here:
Javascript: Do I need to put this.var for every variable in an object?
(6 answers)
Closed 8 years ago.
After using push() method, I print the item arr[i].title into console and it shows 'undefined', instead of "God father 1". See line 12 of the code.
Here is the code:
<!doctype html>
<html lang="en">
<head>
<title> Document Object Properties </title>
<meta charset="utf-8">
<script>
window.onload = init;
function init() {
var arr = [];
for (var i=0; i < 3; i++) {
arr.push(new Movie("God father " + i,1970,"Cowboy",15,["13:00","17:00","21:00"]));
console.log("Array item: " + arr[i].title); // WHY Undefined???
for (var j=0; j < 3; j++) {
//arr[i].showtimes[j] = "0" + i + ":00";
}
}
var div = document.getElementById("result");
div.innerHTML =
"Movie: " + arr[0].title + "<br>" +
"Year: " + arr[0].year + "<br>" +
"Genre: " + arr[0].genre;
}
function Movie(title,year,genre,rating,showtimes) {
var title= " ";
var year= 2000;
var genre= " ";
var rating= 15;
var showtimes= [];
}
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
You are not creating any properties in the object constructor, you are just overwriting the parameters with values.
You want to take the parameters and put in properties:
function Movie(title,year,genre,rating,showtimes) {
this.title = title;
this.year = year;
this.genre = genre;
this.rating = rating;
this.showtimes = showtimes;
}
You're creating variables with var inside Movie, but that's not how you add properties to objects. You have to assign the values to this.
function Movie(title, year, genre, rating, showtimes) {
this.title = title;
this.year = year;
// etc
}

Exporting Recordset to an HTML Table (Object Doesn't Support This Property or Method)

I can't seem to figure out as to why I would be getting an error "Object Doesn't Support This Property or Method" As far as I am aware, I seem to be doing everything by the book.
Any help is greatly appreciated.
Thanks
function test() {
try {
alert("running function test...")
var cn = new ActiveXObject("ADODB.Connection")
var sql = "SELECT * FROM tbl_rssims"
var db = "G:\\AS\\Asf\\ASF\\RSSIMS\\db\\rssims.mdb"
cn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + db + "")
rs = cn.Execute(sql);
var trs = [ ];
while ( ! rs.EOF )
{
var tr = [ ];
for ( var td = 1; td <= 2; ++td )
{
if ( ! rs.EOF )
{
var flds = [ ];
for ( var f = 0; f < rs.fields.length; ++f )
{
flds.push( rs.fields(f).value );
}
trs.MoveNext();
tr.push( flds.join("<br/>") );
} else {
tr.push( " " );
}
}
trs.push( "<td>" + tr.join("</td><td>") + "</td>\n" );
}
rs.close
cn.close
var html = '<!DOCTYPE html>\n'
+ "<html><body" +
+ '<table style="border: none; table-layout: fixed; width: 100%; text-align: left;" cellpadding="0" cellspacing="0">\n'
+ "<tr>" + trs.join("</tr><tr>") + "</tr>"
+ '</table></body></html>';
window.open('','').document.write(html)
}//end of try
catch(e) {
alert(e.description)
}
}//end of function
the question is very hard to work with because you do not tell us what line is throwing the error... however it looks like you are trying to call a function when you likely want to access the array here:
flds.push( rs.fields(f).value );
change this to
flds.push( rs.fields[f].value );
and you should be ok.
edit
now we can deal with the window.open method...
var win = window.open("","");
win.onload = function() {
win.document.documentElement.innerHTML = html;
};
You can try this and see if it helps. But again, knowing where the actual error is would be much more helpful.
it turns out the problem with the object was trs.movenext() where it should have been rs.Movenext(), there was nothing wrong with the actual writting of the HTML.
Thanks for everyones help though.

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

Categories