I have the following code in my cshtml Razor page:
@foreach (var localRecord in Model.electionData)
{
<div >
<label for="@localRecord.ElementID" >@localRecord.FundName</label>
<div >
<input type="number" id="@localRecord.ElementID" min="@localRecord.MinPct" max="@localRecord.MaxPct" value="0">
<input type="number" hidden value="@localRecord.HostFID" />
</div>
</div>
}
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
};
sendData.push(data);
}
});
$.ajax({
type: "POST",
url: "@Url.Action("Summary")",
dataType: "text",
data: { 'formData': sendData },
success: function (msg) {
$("form").attr('action', '/OnlineEnrollment/Summary');
$("form").submit();
},
error: function (req, status, error) {
console.log("in ajax error function");
console.log(req);
console.log(status);
console.log(error);
console.log(msg);
}
});
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.
CodePudding user response:
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();