Skip to content Skip to sidebar Skip to footer

Getting Closest Hidden Value Outside TR

How can I get the the value of the hidden field with the class 'OriginalSuggestedQty' when a checkbox within the row is checked? Here is what the HTML looks like: ).prev()

That will step up until it reaches the TR and then select the immediately preceding DOM element, which is the input.
Is this correct or will you have other elements between the TR and the input?


Solution 2:

If the HTML has the same structure throughout your page.

so:

input
table > tbody > tr > td > checkbox

I wouldn't use jQuery (pretty heavy functions, with lots of iterations) to do such a simple DOM traversal:

Just do this:

$(".suggested").change(function() {
  if ($(this).is(":checked")) {
      //refer to this, without jQuery wrapper
      var originalVal = $(this.parentElement.parentElement.parentElement.parentElement.previousElementSibling.querySelector("input.OriginalSuggestedQty")).val();
  }
 }

This will select the input by going up to parents (great-great-grandparent table), select its brother that is before him previousElementSibling (prevent selecting of textnodes), then use querySelector to select the correct element.

Finally wrap it in a jQuery-object to allow jQuery ninja to be performed.

However I would use an alternative solution:

Your inputs all have an id: items_1__SuggestedQty. Why not give every input a corresponding data-id attribute:

<input class="OriginalSuggestedQty" data-id="items_1__SuggestedQty"  type="hidden" value="5">

Now you can select easily by doing this:

$(".suggested").change(function() {
    if ($(this).is(":checked")) {
       var originalVal = $("input[data-id='"+$(this).prev().attr("id")+"']").val();
       $(this).closest('tr').find('.SuggestedQty').val(originalVal);
    }
});

input[data-id='"+$(this).prev().attr("id")+"']" this bit will select the element that contains a data-attribute matching the id of the input that is adjacent to the checkbox. This way the link between the elements is more robust. If in the future something changes in the HTML structure the bond will not be broken.


Post a Comment for "Getting Closest Hidden Value Outside TR"