简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM