Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get parent attribute value in jQuery

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" class="form-control" name="txt" required>
  </div>
</div>

What I’m missing here ?

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" class="form-control" name="txt" required>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading