How to get value from an input using jquery?

7

The following line:

<a id="asociar-1500" style='color: #004881' href="#" title='Asociar al Proveedor' class="btn btn-danger"><input type="hidden" value = "true"></>

It generates the following HTML:

<a id="aosciar" class="btn btn-danger" title="Asociar al Proveedor" href="#" style="color: #004881">
<input type="hidden" value="true">
</a>

I would like to know how to get the Value of the Input that is in Hidden , for that I am testing with this jquery function:

$('a[id^=asociar-]').click(function (e) {

e.preventDefault();

var inputs = (this).getElementsByTagName('input');

console.log(inputs[0]);
var asociado = inputs[0].attr('value');

console.log(asociado);

});

But I have not managed to enter the input.

    
asked by jose luis garcia 06.05.2016 в 17:44
source

2 answers

5

To get the value (value attribute) of a field input or select or textarea use val() See jQuery documentation .

$('a[id^=asociar-]').click(function (e) {

  e.preventDefault();

  var inputs = $('input');

  var asociado = $(inputs).val();

  console.log(asociado);

});

You must create a jQuery object with the element you get in inputs , so you can use the val() method of jQuery.

More information about the jQuery objects in the following link: link

You could also do it this way, assuming you do not need the inputs variable afterwards:

$('a[id^=asociar-]').click(function (e) {
  e.preventDefault();
  var asociado = $('input[type=hidden]').val();
  console.log(asociado);
});
    
answered by 06.05.2016 / 17:46
source
9

Do not use attr use val instead

var asociado = inputs[0].val();// es como un get
  

If you change var inputs = (this) .getElementsByTagName ('input'); by var   inputs = $ ('input')

Explanation:

In this case var inputs = (this).getElementsByTagName inputs is not a object of jQuery , therefore it has no associated method of jQuery

On the other hand, when you invoke inputs =$('input') , you add a wrapper that converts inputs to jQuery object and test your object of all available methods

    
answered by 06.05.2016 в 17:45