Solved

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

Posted on 2009-04-05
14
419 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
ID: 24073952
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
ID: 24073974
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
ID: 24074437
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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24076312
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
ID: 24076783
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
ID: 24076846
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
ID: 24077254
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
 

Author Comment

by:designersx
ID: 24103717
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
ID: 24103857
Try this:

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

Accepted Solution

by:
Roger Baklund earned 50 total points
ID: 24103874
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
ID: 24103952
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
ID: 24103977
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
ID: 24103995
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
ID: 24104053
Yes, see the other question. :)
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Jquery GMAP3 Hierarchy 1 24
php checkbox validation 5 27
send post values 7 26
Scroll 5 news at a time. 4 25
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

813 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

19 Experts available now in Live!

Get 1:1 Help Now