How do I get a specific element from several of the same class via jquery?

0

Well, this is probably an extremely simple thing, but I'm trying to figure it out:

Assuming a code

<input type = "text" class = "campos" value = "texto1">
<input type = "text" class = "campos" value = "texto2">
<input type = "text" class = "campos" value = "texto3">
<input type = "text" class = "campos" value = "texto4">

Is there a way to get input with text3 via jquery? With pure javascript I would use

var texto = document.getElementsByClassname("campos")[2].value

but $(".campo")[2].val() does not work.

    
asked by anonymous 31.05.2017 / 18:48

3 answers

0

Do this:

let el = $('[value="texto3"]');

console.log(el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" class = "campos" value = "texto1">
<input type = "text" class = "campos" value = "texto2">
<input type = "text" class = "campos" value = "texto3">
<input type = "text" class = "campos" value = "texto4">

Or if you want to always get the 3rd element:

let el = $('.campos').get(2);

console.log(el.value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" class = "campos" value = "texto1">
<input type = "text" class = "campos" value = "texto2">
<input type = "text" class = "campos" value = "texto3">
<input type = "text" class = "campos" value = "texto4">
    
31.05.2017 / 18:50
0

Use the eq () selector, example:

console.log($('.campos:eq(2)').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" class = "campos" value = "texto1">
<input type = "text" class = "campos" value = "texto2">
<input type = "text" class = "campos" value = "texto3">
<input type = "text" class = "campos" value = "texto4">
    
31.05.2017 / 18:55
0

You can also get the id of the field, there you will get a specific field, even if they belong to the same CSS class. To call the id, just put # before the desired field id:

console.log($('#text2').val());
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><inputtype="text" id= "text1" class = "campos" value = "texto1">
<input type = "text" id= "text2" class = "campos" value = "texto2">
<input type = "text" id= "text3" class = "campos" value = "texto3">
<input type = "text" id= "text4" class = "campos" value = "texto4">
    
31.05.2017 / 19:03