How can I pass a Razor for loop variable's ID to javascript

535 Views Asked by At

I am trying to insert the hyphen(-) (xxx-xx-xxxx) when typing in the Social Security number on each row. My script works fine when Social Security # is not in a loop or array. I can't figure out how to implement the id properly in javascript. SSN ID of <input asp-for="@Model.RecordList[i].SSN" in the for loop renders as RecordList_0__SSN for the first row and increments by 1 for each row. I understand that, but how do I get that value in the javascript.

I have the same issue with <input id="maskedSSN" field. I get it fine for the first row, but I need to append the index value to the input field ID and get it in script. How do I add the index value to the ID name?

HTML:

for (int i = 0; i < Model.RecordList.Count; i++)
                {
                    <tr>
                        <td>
                            @Html.CheckBoxFor(m => @Model.RecordList[i].Resolve, @Model.RecordList[i].Resolve)
                            @*<input asp-for="@Model.RecordList[i].Resolve" type="checkbox" class="form-control_checkbox" value="@Model.RecordList[i].Resolve" />*@
                        </td>                    
                        <td>
                            <div>
                                <input asp-for="@Model.RecordList[i].RetirementNumber" class="form-control_text w-100" maxlength="13" disabled="disabled" />
                                <input asp-for="@Model.RecordList[i].RetirementNumber" type="hidden" id="RetirementNumber" />
                            </div>
                        </td>
                        <td><div><input asp-for="@Model.RecordList[i].FirstName" class="form-control_text w-100" /></div></td>
                        <td><div><input asp-for="@Model.RecordList[i].LastName" class="form-control_text w-100" /></div></td>
                        <td><div><select asp-for="@Model.RecordList[i].Fund" class="form-control_selectbox w-100" asp-items="@(List<SelectListItem>)@Model.FundList"></select></div></td>
                        <td>
                            <div>
                                <select asp-for="@Model.RecordList[i].Code" class="form-control_selectbox w-100" asp-items="@(List<SelectListItem>)@Model.IrsOfficesList"></select>
                            </div>
                        </td>
                        <td>
                            <div class="ssn_format">
                                <input id="maskedSSN" class="masked_ssn form-control_text w-100" maxlength="12" />
                                <input asp-for="@Model.RecordList[i].SSN" oncopy="return false" onpaste="return false" oncut="return false" class="w-100 form-control_text read-only-limited-mode" maxlength="11" style="display:none" />
                            </div>
                        </td>
                        <td><div><input asp-for="@Model.RecordList[i].MonthlyDeduction" asp-format="{0:#####.00}" type="number" step="0.01" class="form-control_text w-100" /></div></td>

                    </tr>
                }

The javascript:

$(document).ready(function () {
           
            $("#maskedSSN").on("cut copy paste", function (e) {
                e.preventDefault();
            });
            $("#maskedSSN").mask('000-00-0000', { 'translation': { 0: { pattern: /[0-9*]/ } } });
            $("#maskedSSN").on("keyup", maskSSN);
            $("#maskedSSN").val($("#RecordList_SSN").val());
            $("#maskedSSN").keyup();


        });
        function maskSSN2() {
            var newMaskedValue = "";
            var currentMaskedValue = $("#maskedSSN").val();
            var tail = "";
            var front = "";
            getInputBeforeMask();
            if (currentMaskedValue.length >= 6) {
                front = currentMaskedValue.substring(0, 6);
                tail = currentMaskedValue.substring(6);
                front = front.replace(new RegExp("[0-9]", "g"), "*");
            }
            else {
                front = currentMaskedValue;
                front = front.replace(new RegExp("[0-9]", "g"), "*");
            }

            newMaskedValue = front + tail;
            $("#maskedSSN").val(newMaskedValue);
        }

        function getInputBeforeMask() { 
            var ssn = $("#RecordList_SSN").val();
            var maskedSsn = $("#maskedSSN").val();
            alert("ssn=" + ssn + " un=" +  maskedSsn) 
            if (ssn.length < maskedSsn.length) {
                ssn = ssn + maskedSsn.substring(ssn.length);
            }
            else {
                ssn = ssn.substring(0, maskedSsn.length);
            }
            $("#RecordList_SSN").val(ssn);
        }
2

There are 2 best solutions below

2
mj1313 On

I have the same issue with <input id="maskedSSN" field. I get it fine for the first row, but I need to append the index value to the input field ID and get it in script. How do I add the index value to the ID name?

Set a variable in the for loop, and assign the id to it, then use this variable as the ID of the input like below:

@for (int i = 0; i < Model.RecordList.Count; i++)
{
    var maskedSSNId = "maskedSSN_" + i;
    <tr>
        <td>
            <div class="ssn_format">
                <input id="@maskedSSNId" class="masked_ssn form-control_text w-100" maxlength="12" />
                <input asp-for="@Model.RecordList[i].SSN" oncopy="return false" onpaste="return false" oncut="return false" class="w-100 form-control_text read-only-limited-mode" maxlength="11" style="display:none" />
            </div>
        </td>
    </tr>
}

SSN ID of <input asp-for="@Model.RecordList[i].SSN" in the for loop renders as RecordList_0__SSN for the first row and increments by 1 for each row. I understand that, but how do I get that value in the javascript.

You can get the length of RecordList in js in this way:

var lenght = @Model.RecordList.Count;

Then you can do the loop to get each row's value with the specified id

<script>
    var lenght = @Model.RecordList.Count;
    var i;
    for (i = 0; i < lenght; i++) {
        console.log($("#RecordList_" + i + "__SSN").val());
    }
</script>
0
Hiwater On

Thanks @mj1313. That was very helpful. You gave me what I needed to make the script work. I am applying the input mask as each character is typed (onkeyup) so I modified html and javascript. I modified the html and javascript a little beyond just applying and getting the correct ID's. The code below is working perfectly know.

The HTML:

for (int i = 0; i < Model.RecordList.Count; i++)
                {
                    var rowId = i;
                    <tr>
                        ....
                        <td>
                            <div>
                                @Html.TextBoxFor(m => @Model.RecordList[i].SSN, new { @id = "RecordList_" + rowId + "__SSN", @class = "form-control_text w-100", @onclick = "maskedSSN(" + rowId + ")" })
                            </div>
                        </td>
                        ....
                    </tr>
                }

The javascript:

function maskedSSN(rowID) {
            $("#RecordList_" + rowID + "__SSN").on("cut copy paste", function (e) {
                e.preventDefault();
            });
            $("#RecordList_" + rowID + "__SSN").mask('000-00-0000', { 'translation': { 0: { pattern: /[0-9*]/ } } });
            $("#RecordList_" + rowID + "__SSN").on("keyup", maskSSN2(rowID));
            $("#RecordList_" + rowID + "__SSN").keyup();
        };

        function maskSSN2(rowID) {
            var newMaskedValue = "";
            var currentMaskedValue = $("#RecordList_" + rowID + "__SSN").val();
            var tail = "";
            var front = "";
            getInputBeforeMask2(rowID);
            if (currentMaskedValue.length >= 6) {
                front = currentMaskedValue.substring(0, 6);
                tail = currentMaskedValue.substring(6);
                front = front.replace(new RegExp("[0-9]", "g"), "*");
            }
            else {
                front = currentMaskedValue;
                front = front.replace(new RegExp("[0-9]", "g"), "*");
            }

            newMaskedValue = front + tail;
            $("#RecordList_" + rowID + "__SSN").val(newMaskedValue);
        }

        function getInputBeforeMask2(rowID) { 
            var ssn = $("#RecordList_" + rowID + "__SSN").val();
            if (ssn.length < maskedSsn.length) {
                ssn = ssn + maskedSsn.substring(ssn.length);
            }
            else {
                ssn = ssn.substring(0, maskedSsn.length);
            }
        }