How to pick a specific element between several of the same class via jquery?

Asked

Viewed 1,188 times

0

Guys, this is probably something extremely simple but I’m struggling to solve:

Assuming a code word

<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 the text3 via jquery? With pure javascript I would use

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

but $(".campo")[2].val() doesn’t work.

3 answers

0


Do it like 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>
<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">

Or if you always want to get the third guy:

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>
<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">

  • I liked . get(). So I can use a for to go through all the fields in search of a specific value. I ended up using Document.getElementsByClassName because I needed to put it to work urgently. As soon as possible I will change to leave standardized c/ Jquery. Thanks

0

Use the selector switch eq(), example:

console.log($('.campos:eq(2)').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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">

0

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

console.log($('#text2').val());
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<input type = "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">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.