jQuery accessing previous element value

I have the following code in my cshtml Razor page:

 @foreach (var localRecord in Model.electionData)
      <div class="row">
           <label for="@localRecord.ElementID" class="col-sm-9 col-form-label text-left">@localRecord.FundName</label>
           <div class="col-sm-3">
                <input type="number" class="form-control election" id="@localRecord.ElementID" min="@localRecord.MinPct" max="@localRecord.MaxPct" value="0">
                <input type="number" hidden value="@localRecord.HostFID" />

And I have the following jQuery code which executes when the user clicks on a submit button:

 var sendData = [];
 var fundName = "";
 var percent = 0;
 var fund = 0;
 var data = {};

 $('.election').each(function () {
       percent = parseInt($(this).val());
       if (percent > 0) {
           fund = $(this).next().val();
           fundName = $(this).prev().prev().val();
           console.log("fundName = " + fundName);
           data = {
               'fund': fund,
               'fundName': fundName,
               'percent': percent
       type: "POST",
       url: "@Url.Action("Summary")",
       dataType: "text",
       data: { 'formData': sendData },
       success: function (msg) {
           $("form").attr('action', '/OnlineEnrollment/Summary');
       error: function (req, status, error) {
           console.log("in ajax error function");

When the code runs, I am able to pick up the percent value from $(this).val() and I am able to pick up the fund value from $(this).next().val(). I have been unable to pick up the fund name value. I have tried $(this).prev().val() and $(this).prev().prev().val(). Both give me undefined.

Any suggestion?

Thank you.

>Solution :

The fund name is not previous to the .election object. It’s previous to the parent of the .election object.

Also, the element with the fund name is not an input field, so it doesn’t have a value. It’s a <label>, so use .text() to get its contents.

So use

fundName = $(this).parent().prev().text();

Leave a Reply