user2909855 user2909855 - 1 month ago 7
Javascript Question

get the value of an input near the href

I am trying to write a jquery statement

Here is the HTML code:

<tr role="row" class="odd">
<td class="variant_title">2014 - CYZ51P/18</td>
<td class="">1</td>
<td>
<input name="price[114][1]" value="265700" class="form-control input_prices unmask" autocomplete="off" type="text">
<a data-year="2014" data-variant="CYZ51P/18" href="#" class="analyseItemChannel green">
</td>
</tr>
<tr role="row" class="even">
<td class="variant_title">2013 - NMR71E22/24</td>
<td class="">0</td>
<td>
<input name="price[111][1]" value="0" class="form-control input_prices unmask" autocomplete="off" type="text">
<a data-year="2013" data-variant="NMR71E22/24" href="#" class="analyseItemChannel green">
</td>
</tr>


So, what I am looking for is when the user click on the (a href) I need to get the data which is in the input near that (a href).

Here is my jquery, and what didn't work for me:

$("a.analyseItemChannel").on('click', function (event)
{
event.preventDefault();

price = $('.input_prices', this).val();
console.log(price);
price = $(this).closest('.input_prices').val();
console.log(price);
});


Any suggestions,
Thank you,

Answer

You should use prev instead of closest in this case.

prev: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

closest: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

$("a.analyseItemChannel").on('click', function (event)
{
    event.preventDefault();

    var price = $(this).prev('.input_prices').val();
    console.log(price);
});