Fabrizio Mazzoni
Fabrizio Mazzoni

Reputation: 1909

jQuery get element attribute from nested element

I'm in a situation as follows:

<span class="inputgrp">
  <span class="additem">

  </span>
</span>
<input type="text" avl="abc">

I'm trying to get the value of the attribute avl from the input with a click event on class="inputgrp"

I have tried with:

$(".additem").click(function () {
  var v = $(this).parent().find("input:text").attr("avl")
})

and

$(".inputgrp").click(function () {
  var v = $(this).prev("span").next("input:text").attr("avl")
})

But without success. Would appreciate some guide as I have no clue what I am dong wrong.

Upvotes: 0

Views: 88

Answers (3)

lotfio
lotfio

Reputation: 1936

use a data-avl="" attribute on your html input element and in jQuery use .data('avl') to get the value of the attribute

$(".inputgrp").click(function() {

  alert($(this).next("input:text").data("avl"));

})

Upvotes: 0

DoXicK
DoXicK

Reputation: 4812

.find searches for children of the current element. The input is not a child but a sibling of .inputgrp

$('.inputgrp').on('click',function() {
    var v = $(this).siblings('input[data-avl]').attr('data-avl');
});
  • Use data-avl as an attribute to make it valid.
  • Use the .sibling() function to select any of the siblings
  • If the input element is always going to be the next element, use the .next() function

Upvotes: 0

guradio
guradio

Reputation: 15555

$(".inputgrp").click(function() {

  alert($(this).next("input:text").attr("data-avl"))

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="inputgrp">
  <span class="additem">
1
  </span>
</span>
<input type="text" data-avl="abc">

  1. Use data attribute since avl is not a valid attribute
  2. use .next() since input is next to the click element

Upvotes: 3

Related Questions