HTML:
<a onclick="funcion(this)" value="4">Un Nombre</a>
JAVASCRIPT:
<script>
function(elemento){
console.log(elemento.value);
}
</script>
this is giving me back
undefined
HTML:
<a onclick="funcion(this)" value="4">Un Nombre</a>
JAVASCRIPT:
<script>
function(elemento){
console.log(elemento.value);
}
</script>
this is giving me back
undefined
value=""
is not a valid attribute for a link (anchor).
The correct way would be to add an attribute data-value
<a onclick="mifuncion(this)" data-value="4">Un Nombre</a>
Here you can see the specific attributes supported by <a>
: link
You can also see the global attributes that can be included in <a>
:
link
To get this attribute data-value
through jQuery, we can use the method data () from jQuery passing as a parameter the text of the name of the attribute after data-
, you also need to define the function (the name):
<script>
function mifuncion(elemento) {
console.log($(elemento).data('value'));
}
</script>
Using JavaScript vanilla is just as easy, with the difference that there is no external library / framework, we only use the property dataset and again the name of the attribute after the text data-
:
<script>
function mifuncion(elemento) {
console.log(elemento.dataset.value);
}
</script>
The <a>
tag does not have a value attribute in a standard way, you can define it but it does not have one
You will see that the value is not a valid attribute, but the same with jquery you could implement
$(function(){
$('a').click(function(e){
alert($(this).attr('value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<a value="4">Un Nombre</a>
Consider:
<script>
must be accessible before. An easy way to fix it is to load it in <head>
. value
is not a property that belongs to <a>
, therefore, you should recover the value with .getAttribute()
. MostrarValor
.
function MostrarValor(elemento){
console.log(elemento.getAttribute("value"));
}
<a onclick="MostrarValor(this);" value="4">Un Nombre</a>
Again, loading it into <head>
and defining a name for the function. This time, we use .attr()
:
function MostrarValor(elemento){
console.log($(elemento).attr("value"))
}
<!-- Ponemos la referencia a jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Tu HTML -->
<a onclick="MostrarValor(this);" value="4">Un Nombre</a>