I want to fetch the parent attribute but it returns undefined jquery

146 views Asked by At

This is my code:

$(document).on('click', '.setting', function(e){
 alert($(this).parent().data('fieldtype'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="field">
  <div class="col-md-9 col-sm-6 col-xs-6 pad" style="">
    <textarea class="form-control field" name="key1" rows="3" data-fieldtype="test" data-group="">demo</textarea>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer movefield" data-key="1">
    <div><span class="glyphicon glyphicon-arrow-up"></span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer setting" data-key="1">
    <div><span class="glyphicon glyphicon-cog">click me</span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer field-remove" data-key="1">
    <div>x</div>
  </div>
</div>

Now the problem is not getting the value of data-fieldtype, as this method it returns undefined. And also suggest for getting the value of data-group as currently this one is blank

1

There are 1 answers

0
Mohammad On BEST ANSWER

Because the textarea isn't parent of .setting. Parent of it is #field and you should find textarea in it.

$(this).parent().find('[data-fieldtype]').data('fieldtype')

$(document).on('click', '.setting', function(e){
  console.log(
    $(this).parent().find('[data-fieldtype]').data('fieldtype')
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="field">
  <div class="col-md-9 col-sm-6 col-xs-6 pad" style="">
    <textarea class="form-control field" name="key1" rows="3" data-fieldtype="test" data-group="">demo</textarea>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer movefield" data-key="1">
    <div><span class="glyphicon glyphicon-arrow-up"></span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer setting" data-key="1">
    <div><span class="glyphicon glyphicon-cog">click me</span></div>
  </div>
  <div class="col-md-1 col-sm-2 col-xs-2 pad pointer field-remove" data-key="1">
    <div></div>
  </div>
</div>