Solved

How to pass the id in document.getEementById() ?

Posted on 2009-04-05
14
413 Views
Last Modified: 2012-05-06
we write document.getElementById("any_id")  we write the specific id in this.

if suppose i have 5 images having their id's id=1 , 2 , 3, 4, 5 . now i want that on clicking any image , its id should be passed to   document.getElementById(" id should be passed here. ")

Is it possible by some or the other way?
0
Comment
Question by:designersx
  • 7
  • 7
14 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
In a onclick event, "this.id" is the id of the element. "this" id the element itself, the object that would be returned by document.getElementById(this.id). So, in this case, it is better to just use "this".

If this does not help, show your code.
0
 

Author Comment

by:designersx
Comment Utility
i am calling another page and in that i am calling a function, so i think we can't use this.

sir i will be giving the code  after some time after going to office.
0
 

Author Comment

by:designersx
Comment Utility
i have called image function on the image click.  now in the script i have defined the function image.  my images are coming from the database and displayed on the front end. now i want to pass id of the image to document.getElementbyid and since i am also using the ajax see the quickstart.js file, u will see the image function to be defined. here i am finding problem in getting the id of the image in documetn.getelementbyid.
edit_complete.php file
 

<?php

include('connection.php');

?>

<html>

<head>

  <title>PHP</title>

    <script type="text/javascript" src="quickstart.js"></script>

<script>

function image(img_id){

var v='	<?php 

		$sql="select img from images";

		$query=mysql_query($sql) or die("query not executed".mysql_error());

		$rec=mysql_fetch_array($query);

		echo $rec['img'];

	?>';

	

	document.getElementById("maindiv").src = v;	

}

</script>

</head>

<body>

<form action="add1.php" name="abc" method="post"  enctype="multipart/form-data"> 

<a href="edit_complete.php?id=<?php echo $rec['img_id']?>"><img id="<?php echo $rec['img_id'];?>" src="<?php echo $rec['img'];?>" onClick="image(<?php echo $rec['img_id']?>)"/></a>

<input type="submit" name="abc" value="Add"/></td></tr>

</form>

</body>

</html>
 
 

quickstart.js
 
 

function image(id)

{   //var r = id.length;

	//alert(r)

	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)

  {

	  for(i=0;i<id;i++){

    	id = encodeURIComponent(document.getElementById(+i).value);  // error is here

	}

    xmlHttp.open('get', 'background.php?id=' + id, true);  

    xmlHttp.onreadystatechange = background;

    xmlHttp.send(null);

  }

  else

    setTimeout('process()', 1000);

}
 

function background()

{ //alert("called")

	if(xmlHttp.readyState == 4){

		var response = xmlHttp.responseText;

		document.getElementById('maindiv').innerHTML = response;

	}

}

Open in new window

connection.txt
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
There seems to be multiple problems here.

There seems to be two javascript functions named "image". That won't work. The first defined (in the file quickstart.js) will be overwritten by the one defined in the main file. In other words, line 41 marked "// error is here" is never executed.

This is wrong:

document.getElementById(+i).value

It can't be "+i". Just "i":

document.getElementById(i).value


What is the purpose of the lines 38-42 ? The id is sent as a parameter to this function. xmlHttp is not defined. If it is not defined in some part of your code that you are not showing, it will fail. setTimeout('process()', 1000) will fail after 1 second if the function process() is not defined.

The connection file is included. It calls a function check_login($username,$password), but this function does not seem to be defined?

The image() function defined in edit_complete.php is odd. The PHP code with the SQL select statement fetches all rows, but only the first found is put into the variable $rec. The vaule of $rec['img'] is output, if the value for instance is "MyImg.jpg" then the effective javascript statement becomes:

var v=' MyImg.jpg';

Note the initial space, it should not be there. Change "var v=' <?php" into "var v='<?php".

The PHP code will be executed once, before the page is sent to the browser. When clicking the image:

onClick="image(<?php echo $rec['img_id']?>)"

...the same value for the image id will be used all the time, and the same image will be assigned to the src property of the element with id="maindiv":

document.getElementById("maindiv").src = v;  

The element "maindiv" is not defined in the code provided, if "maindiv" is defined elsewhere, it must be an image, not a div. div elements does not have a src property. In any case, the value of v is constant, it is not ajax enabled.

When the form is submitted, add1.php will be executed, but there are no parameters from the form, except for abc=Add.

If you can explain what exactly you are trying to do, I might have a suggestion for a way to solve it.
0
 

Author Comment

by:designersx
Comment Utility
really a lot of thanks for ur reply sir

1) yes u are saying right. i have called image function, this is my biggest mistake.ok now in line 25 i am passing the image id and calling the function image.

 purpose of the lines 38-42 - > this function is called when the image is clicked an id is passed in the argument. nowin this line of code    document.getElementById( here the id of the image should come   ).value    ( This is the main problem).

2) i have my all code working except i am not able to pass the id inside  document.getElementById

what i think is that it is not possible what i am trying to do
[background.php]
 

<?php

$imgid = $_REQUEST["id"];
 

mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error()); 

mysql_select_db("vistaprint");
 

echo $sql="select * from images where img_id=$imgid";

$query=mysql_query($sql) or die("query not executed".mysql_error()); 

$rec=mysql_fetch_array($query) or die("data not fetched".mysql_error());

?>

<script>

backimage[<?php echo $rec['img_id'] ?>]="url('<?php echo $rec['img']; ?>')";

var a=backimage[<?php echo $rec['img_id']?>];

document.getElementById("maindiv").style.background = a ;

</script>

Open in new window

0
 

Author Comment

by:designersx
Comment Utility
what i think is that it is not possible what i am trying to do , the reason is that in

document.getElementById()  here always the id should be fixed.
i don't know i can be wrong. please tell me.
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
You can use a variable as a parameter for document.getElementById(), but the variable can not be prefixed with a + character. "+i" does not work, "i" works, if "i" is a variable: document.getElementById(i).

The loop in your code, lines 40-42:

for(i=0;i<id;i++){
        id = encodeURIComponent(document.getElementById(i).value);
        }

This loop is setting id to be equal to the value of the element with id=0, 1, 2 ... up to but not inclucing "id". Each iteration of the loop overwrites the previous value of the id variable. The effect is the same as this:

id = encodeURIComponent(document.getElementById(id-1).value);

Is it supposed to find the PREVIOUS item? If not, just remove the lines 38-42. If it is, use the line above instead of lines 40-42.

What type of element has id 0, 1, 2 ...? Image elements does not have a "value" property.

Then you call the php script with parameter id, using ajax:

xmlHttp.open('get', 'background.php?id=' + id, true);

In background.php you find an image record in the database based on the id, and write the query and some javascript. The javascript puts the image name in a variable "backimage[id]", and puts that variable into "a", and puts the "a" variable into style.background of the elmenent with id="maindiv". It would be more effective to put it in the style.background property in the first place.

When the ajax call returns, the javascript produced by the PHP is put into "maindiv" content (using innerHTML), and the javascript is executed.

I still don't know what you are trying to do. It is easier to help you if you explain what you are trying to achieve.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:designersx
Comment Utility
sir please see my modified code. i actually want to bring the value of id of the clicked image into document.getelementbyid.

please leave all the issues except this line of code,

id = document.getElementById(here i want to bring the value of the id of the image,how can i accomplish this???).value;  

id is coming from the php page and is passed to the function image.
yogesh
[edit_complete.php]

 

<?php

include('connection.php');

?>

<html>

<head>

  <title>PHP</title>

    <script type="text/javascript" src="quickstart.js"></script>

</head>

<body>

<form action="add1.php" name="abc" method="post"  enctype="multipart/form-data"> 

<a href="edit_complete.php?id=<?php echo $rec['img_id']?>"><img id="<?php echo $rec['img_id'];?>" src="<?php echo $rec['img'];?>" onClick="image(<?php echo $rec['img_id']?>)"/></a>

<input type="submit" name="abc" value="Add"/></td></tr>

</form>

</body>

</html>

 

 

[quickstart.js]

 

 

function image(id) //(this id contains the id of the image that is clicked.)

{   

    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)

  {

    id = document.getElementById(here i want to bring the value of the id of the image,how can i accomplish this???).value;  

    xmlHttp.open('get', 'background.php?id=' + id, true);  

    xmlHttp.onreadystatechange = background;

    xmlHttp.send(null);

  }

}

 

function background()

{ 

        if(xmlHttp.readyState == 4){

                var response = xmlHttp.responseText;

                document.getElementById('maindiv').innerHTML = response;

        }

}

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
Try this:

id = document.getElementById(id).value;
0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 50 total points
Comment Utility
It won't work, though. The element with that id is an IMG element, it does not have a "value" property.

The id is passed as a parameter to this function. This might work:

function image(id) //(this id contains the id of the image that is clicked.)
{  
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    xmlHttp.open('get', 'background.php?id=' + id, true);  
    xmlHttp.onreadystatechange = background;
    xmlHttp.send(null);
  }
}
0
 

Author Comment

by:designersx
Comment Utility
i will let u know, actually i have freshly installed windows in a new hard disk and previous hard disk is attached .now i installed mysql in my new windows but i am not able to import the previous tables of mysql into new mysql .so i am facing the great problem. do u have the solution for this, only then i will be able to let u know.
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
You have a separate question about getting the old tables. You need to tell me if the old database was using innodb tables or myisam tables. But let's keep that problem in the other question, where it belongs. :)
0
 

Author Comment

by:designersx
Comment Utility
respected sir,i have already opened a separate this question. i am sorry but can u tell me how do i come to know that i am using innodb tables or myisam tables
0
 
LVL 39

Expert Comment

by:Roger Baklund
Comment Utility
Yes, see the other question. :)
0

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now