Get the value of an element "a" from jQuery

4

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

    
asked by Jónathan Cuellar 04.08.2016 в 04:51
source

3 answers

7

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>
    
answered by 04.08.2016 в 05:10
2

The <a> tag does not have a value attribute in a standard way, you can define it but it does not have one

HTML Tag

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>
    
answered by 04.08.2016 в 05:14
2

From pure JavaScript:

Consider:

  • The javaScript code should be present BEFORE the document is loaded in order to assign the function to it. Therefore, the <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() .
  • You forgot to name the function. We can call it MostrarValor .
  • function MostrarValor(elemento){
        console.log(elemento.getAttribute("value"));
    }
    <a onclick="MostrarValor(this);" value="4">Un Nombre</a>

    With jQuery

    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>
        
    answered by 04.08.2016 в 05:43