简体   繁体   中英

Unable to get closest element with certain class jQuery

I have a function that catches whether the input has changed or not then if the value is exceeding the max it sets the value to the max. So you can not enter a value over the max. But if you try to do this I want to display an error message but I am struggling to get the closest error message. Here is my code;

 $(document).on('keydown keyup', '.quantity input', function(e) { var max = Number($(this).attr('max')); if ($(this).val() > max) { e.preventDefault(); $(this).val(max); $(this).closest('.quant_warn').show(); } else if ($(this).val() < 1) { e.preventDefault(); $(this).val(1); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="quantity"> <label>Quantity: </label> <div class="increment"> <span></span><span></span> </div> <input type="text" value="1" min="1" max="10"> <div class="decrement"> <span></span> </div> <div class="quant_warn" style="display: none;">only 10 in stock</div> </div> 

Since the .quant_warn div isn't a parent of the input but a sibling, you need to use siblings() instead :

$(this).siblings('.quant_warn').show();

NOTE : It will be more efficient to use input event instead of keydown keyup when you track the use inputs.

 $(document).on('input', '.quantity input', function(e) { var max = Number($(this).attr('max')); if ($(this).val() > max) { e.preventDefault(); $(this).val(max); $(this).siblings('.quant_warn').show(); } else if ($(this).val() < 1) { e.preventDefault(); $(this).val(1); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="quantity"> <label>Quantity: </label> <div class="increment"> <span></span><span></span> </div> <input type="text" value="1" min="1" max="10"> <div class="decrement"> <span></span> </div> <div class="quant_warn" style="display: none;">only 10 in stock</div> </div> 

Try this for better solution

 $(document).on('keydown keyup', '.quantity input', function(e) { var max = Number($(this).attr('max')); var val = parseInt($(this).val()); if (val) { if (val > max) { e.preventDefault(); $(this).val(max); $(this).siblings('.quant_warn').show(); } else { $(this).siblings('.quant_warn').hide(); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="quantity"> <label>Quantity: </label> <div class="increment"> <span></span><span></span> </div> <input type="text" value="1" min="1" max="10"> <div class="decrement"> <span></span> </div> <div class="quant_warn" style="display: none;">only 10 in stock</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