Ad

How To Use Jquery Id Selection With Variable

- 1 answer

So I have a section in my script that looks like the following:

$('input[id="TestMyId"]').autocomplete({
    source: availableChoice
 },
});

This works great, I get my autocomplete to fire and I can select from a list of choices, but when I make Test a string variable and try to concatenate it with MyId I can not get it to fire at all:

@{
    var foo = "Test";
}
<body..../>
<script>
    $('input[id="' + @foo + 'MyId"]').autocomplete({
        source: availableChoice
     },
    });
</script>

foo is declared as a global variable in the .cshtml. Not sure why the Id selection is not working when I concatenate the names? Any help would be appreciate it.

Ok I've posted below a bit more detail, Id is FirstNameId in this test case, trying to combine it with the @prefix variable:

    @using System.Collections.Concurrent
    @model MyModel

    @{
        var prefixt = "TestContactInformation";
    }

    @using (Html.BeginForm("MyAction", "MyController"))
    {

    <article class="widget widgetFullPage" data-role="collapsible" data-collapsed="true" id="articlePrimaryContact" style="height:auto">
        <h2>Test Information</h2>

        <table id="tableContactInformation">
            <tr>
                <td style="width: 180px; padding-top: 20px; padding-left: 15px;"><label>Relationship to Policyholder</label></td>
                <td style="width: 50px; padding-top: 15px">@Html.DropDownListFor(x => x.PrimaryContact.ContactRole, (List<SelectListItem>)ViewBag.RelToPolicyList, new { id = @prefixt + "RoleId", style = "width:130px", tabindex = @tabIndexBase + 1 })</td>
                <td style="width: 100px; padding-top: 20px; padding-left: 15px;" id=" titlelable"><label>Title</label></td>
                <td style="width: 200px; padding-top: 20px;padding-left: 12px;" id="TitleText">@Html.TextBoxFor(x => x.PrimaryContact.Title, null, new { id = @prefixt + "TitleId", style = "width:250px", tabindex = @tabIndexBase + 8 })</td>
            </tr>
            <tr [email protected]>
                <td style="width: 150px; padding-left: 15px;"><label>Contact Description</label></td>
                <td style="width: 100px">
                    @Html.TextBoxFor(x => x.PrimaryContact.ContactRoleDescription, null, new { id = @prefixt + "DescriptionId", style = "width:250px", tabindex = @tabIndexBase + 2 })
                </td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px; padding-left: 15px;">
                    <label>First Name</label>
                    @if (@prefixt == "TestContactInformation")
                    {
                        <a id="LearnMore"><img src="~/Images/info.png" alt="" /></a>
                    }
                </td>
                @*<td style="width: 100px;">@Html.TextBoxFor(x => x.PrimaryContact.FirstName, null, new { id = @prefixt + "FirstNameId", style = "width:250px", tabindex = @tabIndexBase + 3 })</td>*@
                <td style="width: 100px;">@Html.TextBoxFor(x => x.PrimaryContact.FirstName, null, new { id = @prefixt + "FirstNameId", style = "width:250px", tabindex = @tabIndexBase + 3 })</td>
                <td style="width: 100px;padding-left: 15px;"><label>Address Line 1</label></td>
                <td style="width: 200px;padding-left: 12px;">@Html.TextBoxFor(x => x.PrimaryContact.AddressLine1, null, new { id = @prefixt + "Address1Id", style = "width:250px", tabindex = @tabIndexBase + 9 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px;"><label>Last Name</label></td>
                <td style="width: 100px; ">@Html.TextBoxFor(x => x.PrimaryContact.LastName, null, new { id = @prefixt + "LastNameId", style = "width:250px", tabindex = @tabIndexBase + 4 })</td>
                <td style="width: 100px;  padding-left: 15px;"><label>Address Line 2</label></td>
                <td style="width: 200px; padding-left: 12px;">@Html.TextBoxFor(x => x.PrimaryContact.AddressLine2, null, new { id = @prefixt + "Address2Id", style = "width:250px", tabindex = @tabIndexBase + 10 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px;"><label>Email</label></td>
                <td style="width: 100px; ">@Html.TextBoxFor(x => x.PrimaryContact.Email, null, new { id = @prefixt + "EmailId", style = "width:250px", tabindex = @tabIndexBase + 5 })</td>
                <td style="width: 100px;  padding-left: 15px;"><label>City</label></td>
                <td style="width: 200px; padding-left: 12px;">@Html.TextBoxFor(x => x.PrimaryContact.City, null, new { id = @prefixt + "CityId", style = "width:250px", tabindex = @tabIndexBase + 11 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px;"><label>Phone</label></td>
                <td style="width: 100px; ">@Html.TextBoxFor(x => x.PrimaryContact.Phone, null, new { id = @prefixt + "PhoneId", @class = "phone", style = "width:250px", tabindex = @tabIndexBase + 6 })</td>
                <td style="width: 100px; padding-left: 15px;"><label>State</label></td>
                <td style="width: 200px; padding-left: 12px;">@Html.DropDownListFor(x => x.PrimaryContact.State, Model.PrimaryContact.StatesList ?? (List<SelectListItem>)ViewBag.StatesList, new { id = @prefixt + "StateId", style = "width:130px", tabindex = @tabIndexBase + 12 })</td>
            </tr>
            <tr style="height: 30px;">
                <td style="width: 100px;  padding-left: 15px; padding-bottom: 20px"><label>Ext.</label></td>
                <td style="width: 100px;padding-bottom: 20px">@Html.TextBoxFor(x => x.PrimaryContact.Ext, null, new { id = @prefixt + "ExtId", style = "width:250px", @class = "numbersOnly", tabindex = @tabIndexBase + 7 })</td>
                <td style="width: 100px;  padding-left: 15px;padding-bottom: 20px"><label>Zip</label></td>
                <td style="width: 200px;padding-left: 12px;padding-bottom: 20px">@Html.TextBoxFor(x => x.PrimaryContact.Zip, null, new { id = @prefixt + "ZipId", @class = "zip", style = "width:250px", tabindex = @tabIndexBase + 13 })</td>
            </tr>
        </table>
    </article>

    }

    <link rel="stylesheet" target="_blank" rel="nofollow noreferrer" href="~/Content/jquery-ui.css" />
    <style>
        .ui-corner-all,
        .ui-corner-top,
        .ui-corner-left,
        .ui-corner-tl {
            border-top-left-radius: 0;
        }

        .ui-corner-all,
        .ui-corner-top,
        .ui-corner-right,
        .ui-corner-tr {
            border-top-right-radius: 0;
        }

        .ui-corner-all,
        .ui-corner-bottom,
        .ui-corner-left,
        .ui-corner-bl {
            border-bottom-left-radius: 0;
        }

        .ui-corner-all,
        .ui-corner-bottom,
        .ui-corner-right,
        .ui-corner-br {
            border-bottom-right-radius: 0;
        }
    </style>

    <script type="text/javascript">
        var availableContacts = [];

        @foreach (var theContact in Model.ContactsList)
        {
            @:availableContacts.push( {value: "@theContact.FirstName, @theContact.LastName, @theContact.City, @theContact.State", label: "@theContact.FirstName, @theContact.LastName" });
        }

        //$("input[id='TestContactInformationFirstNameId']").autocomplete({
        //    source: availableContacts,
        //    select: function (event, ui) {
        //        var firstName = ui.item.value.split(',')[0];
        //        var lastName = ui.item.value.split(',')[1];
        //        var city = ui.item.value.split(',')[2];
        //        var state = ui.item.value.split(',')[3];
        //        alert(firstName);
        //        alert(lastName);
        //        alert(city);
        //        alert(state);
        //    },
        //});

        var theConcated = @string.Format("{0}FirstNameId", @prefixt);
        $("input[id='" + theConcated + "']").autocomplete({
            source: availableContacts,
            select: function (event, ui) {
                var firstName = ui.item.value.split(',')[0];
                var lastName = ui.item.value.split(',')[1];
                var city = ui.item.value.split(',')[2];
                var state = ui.item.value.split(',')[3];
                alert(firstName);
                alert(lastName);
                alert(city);
                alert(state);
            },
        });

    </script>
    <script type="text/javascript" src="~/Scripts/jquery.maskedinput.js"></script>

The commented out section with

$("input id='TestContactInformationFirstNameId']") 

works great, but running the other section with the combined string I get is this:

0x800a1391 - JavaScript runtime error: 'TestContactInformationFirstNameId' is undefined

Any Ideas?

Ad

Answer

OK, after many trials and errors found the following to be working for my case, posting here incase it's helpful to someone else:

$("input[id='@prefixt" + "FirstNameId']")

Or

$("#@prefixt" + "FirstNameId")

Both seems to work, looks like the variable call needs to be inside the quotes.

Ad
source: stackoverflow.com
Ad