When the method onclick
is executed, that method is executed on the context of the element, which means that the onclick
, interprets that name
is the attribute , not a function .
If you execute this code, you will notice how the value of the attribute name
prevails:
<button onclick="alert(name)" name="hola">
imprimir
</button>
So by telling you that name
is not a function it is correct because it is an attribute.
Try accessing the function using the window object, which is where all the global functions belong. For example:
function name(){
console.log("hola mundo");
}
<button onclick="window.name()" name="hola">
imprimir
</button>
Or rename your function to any other name:
//..
while ($resultados=$resultado->fetch_assoc()){
?>
<?php $a=$resultados['email'];?>
<?php $b=$resultados['idcliente'];?>
<ul>
<li><a id="<?php echo $a?>" href="#" onclick="nombre();"><?php echo $a?></a></li>
</ul>
<script type="text/javascript">
function nombre() {
var name = document.getElementById("<?php echo $a?>").innerHTML;
alert(name);
}
</script>
<?php }?>
And another thing. You are generating a function name()
for each iteration that the while
does. Which means that if the while
iterates 5 times, 5 functions with the same name will be created and only the last one will be taken as a reference, not the closest to the click event.
For example:
<?php
for($i = 0; $i < 5; $i++)
{
?>
<button onclick="namef()" name="hola">
imprimir
</button>
<input type="text" id="input_<?php echo $i ?>" value="<?php echo $i ?>"></input>
<script type="text/javascript">
function namef() {
var f = document.getElementById("input_<?php echo $i?>").value;
alert(f);
}
</script>
<?php
}
?>
Regardless of which button you click, it will always print 4. Try to get the definition of the function out of while
and send the id of the element you want the parameter value to the function when the event is done click like this:
<?php
for($i = 0; $i < 5; $i++)
{
?>
<button onclick="namef('input_<?php echo $i ?>')" name="hola">
imprimir
</button>
<input type="text" id="input_<?php echo $i ?>" value="<?php echo $i ?>"></input>
<?php
}
?>
<script type="text/javascript">
function namef(id) {
var f = document.getElementById(id).value;
alert(f);
}
</script>