Home > Back-end >  Find next element above with class
Find next element above with class

Time:05-20

I'm trying to get the value of element with the class price if the quantity is clicked. I continue to get undefined with next() ,find(), closest(). Its at the point that asking should be faster.

$(function() {
  $('input.quantity').click(function() {
    var test = $(this).parent('.qty-price').closest('.price').html();
    alert(test);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li >
  <a href="/" >
    <span >
                <h3>Test Description</h3>
                <span >
                    <span >
                        <input type="number" rel="0"  value="1"  min="0">
                    </span>
    <span >$5.00</span>
    </span>
    </span>
  </a>
  <a href="#remove" ><span >X</span></a>
</li>

CodePudding user response:

Assuming that your input isn't disabled as you said in your comment you can use the following. Note that since your input lies within an anchor you need to stop the click event from bubbling up the DOM.

$(function() {
  $('input.quantity').click(function(e) {
    e.stopPropagation();
    var test = $(this).parent('.qty').next('.price').text();
    alert(test);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li >
  <a href="/" >
    <span >
                <h3>Test Description</h3>
                <span >
                    <span >
                        <input type="number" rel="0"  value="1"  min="0" >
                    </span>
    <span >$5.00</span>
    </span>
    </span>
  </a>
  <a href="#remove" ><span >X</span></a>
</li>

  • Related