tags:

views:

334

answers:

2

Hi there, I am passing hidden value, and getting it into javascript function. I want to pass this value to another page. Before passing when i print it, it gives me [object HTMLInputElement]

$var4 = 1;

echo "<input type='hidden' id='var4' value='$var4'>";

and accessing it in javascript

var y = document.getElementById('var4');
   document.write(y);    //[object HTMLInputElement]

it gives me output as [object HTMLInputElement] instead of 1

Another thing is that I want to pass this value to data.php

".... data.php?q="+y)

is this write, can i pass value like this? Would you suggest me any solution. Thanks in advance.

A: 

document.getElementById returns the html element with the specified id (and hence the HTMLInputElement); read its value to get the required value.

var y = document.getElementById('var4').value;

"...data.php?q="+y is fine. You can read the passed value in the PHP page using $_GET['y']. Just make sure y is not NaN or undefined

Amarghosh
@Amar It worked perfectly, when I just put .value after document.getElementById('var4'). Thank you very much Amar.
Rishi2686
+2  A: 

Well, yes, document.getElementById('var4') gets the HTML element with the id 'var4'. It doesn't give you the value of the HTML element, it gives you the whole element.
y.value would give you the value.

I'm not sure I understand the situation correctly, but if you just want to pass variables from PHP to Javascript, you don't need to create hidden input elements to do so. Rather, use something like this:

<script type="text/javascript" charset="utf-8">
  var myVars = <?php echo json_encode($myVars); ?>;
</script>

This way the variables are directly available as Javascript variables, no getting of elements necessary.

deceze
@deceze It really worked, thank you very much!!!!!. I really appreciate your help. Thanks again.
Rishi2686
@Rishi You should vote on and accept answers in lieu of verbal praise. :)
deceze