简体   繁体   中英

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:

<input class="OriginalSuggestedQty" type="hidden" value="5">
<tr>
    <td >
        <input class="SuggestedQty" id="items_1__SuggestedQty" type="text" value="9">
        <input checked="checked" class="suggested"type="checkbox" value="true">
    </td>
</tr>

This is what i currently have:

$(".suggested").change(function() {
    if ($(this).is(":checked")) {
        var originalVal = $(this).closest('.OriginalSuggestedQty').val();
        $(this).closest('tr').find('.SuggestedQty').val(originalVal);
    }
});

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.

To match the exact HTML shown in the post, you can use this:

$(this).closest('tr').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?

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