Home > Enterprise >  Get parent attribute value in jQuery
Get parent attribute value in jQuery

Time:09-28

I want to get the data-value 'Tomatoe' from this code when the user is typing in the input:

$('input[name=txt]').on('input', function() {
  var module = $(this).closest('[data-value]').val();
  alert(module);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="Tomatoe">
  <div>
    <input type="text"  name="txt" required>
  </div>
</div>

What I'm missing here ?

Thanks.

CodePudding user response:

A <div> has no value, so .val() won't produce anything meaningful. You want the jQuery .data() function:

$('input[name=txt]').on('input', function() {
  var module = $(this).closest('[data-value]').data('value');
  alert(module);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-value="Tomatoe">
  <div>
    <input type="text"  name="txt" required>
  </div>
</div>

  • Related