7 votes

How to get value from an input using jquery?

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 trying 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.

9voto

jasilva Points 4262

Do not use attr used val in his place

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

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

Explanation:

In this case var inputs = (this).getElementsByTagName inputs is not an object of jQuery, therefore you do not have any method associated with the jQuery

Instead, when you invoke inputs =$('input') adds a wrapper that converts inputs to object of jQuery and probee to your object of all the methods available

6voto

Shaz Points 22941

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

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

  e.preventDefault();

  var inputs = $('input');

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

  console.log(asociado);

});

You need to create a jQuery object with the element that you get in inputs, this way you will be able to use the method val() of jQuery.

More information about the objects in jQuery in the following link (in English): http://api.jquery.com/jQuery/

You could also do it this way, assuming that you don't need the variable inputs after:

$('a[id^=asociar-]').click(function (e) {
  e.preventDefault();
  var asociado = $('input[type=hidden]').val();
  console.log(asociado);
});

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X