Change the JavaScript variable to the selected DropDownList

advertisements

I have a table that has a lot of DropDownList that i had change each of the class name depending on the iteration :

<table id="categoryTable" class="table table-striped table-hover">
    <tr class="header">
        <th>
            @Html.DisplayNameFor(model => model.Category)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SubCategory)
        </th>
        <th>New Category</th>
        <th>New Subcategory</th>
        <th></th>
    </tr>

    @if (Model != null) { int i = 1; foreach (var item in Model) {

    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Category)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SubCategory)
        </td>

        <td>
            <input type="hidden" class="varIteration" value="@i" /> @Html.DropDownList("CategoryId", null, "Select Your Category", htmlAttributes: new { @class = "form-control Category" + i })
        </td>
        <td>
            <input type="hidden" [email protected]( "SubCategoryID_CategoryID_initial"[email protected]) value="@i" /> @Html.DropDownList("SubCategoryId", null, "Select Your Subcategory", htmlAttributes: new { @class = "form-control SubCategory" + i })
        </td>
        <td>
            <button type="submit" class="btn">
                <i class="fa fa-check"> Update</i>
            </button>
            @*
            <input type="submit" value="Save" class="fa fa-check" />*@
        </td>
    </tr>
    i++; } }

</table>

I need to change the subcategory values depending on the selected value in the Category using the next script below that doesn't work only on time with the first category drop down list:

$(document).ready(function(e) {
    var iteration = $(".varIteration").val(); // iteration = 1 only
    getSubCat(true, $(".SubCategoryID_CategoryID_initial" + iteration).val(), iteration);
    $(document).on("change", ".Category" + iteration, function(event) {
        getSubCat(false, $(".Category" + iteration).val(), iteration);
    });

    function getSubCat(load, changed, iteration) {
        alert(iteration)
        var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";
        var initialSubCat = $(".SubCategoryID_CategoryID_initial").val();
        var initialCat = $(".SubCategoryID_SubCategoryID_initial").val();
        if (load) {
            $('.Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
        }
        if (initialCat == null) {
            changed = $(".Category" + iteration).val();
        }
        $.getJSON(url, {
            id: changed
        }, function(data) {
            alert(changed);
            $(".SubCategory" + iteration).empty();
            $(".SubCategory" + iteration).append("<option value= '0'>Select Your Subcategory</option>");
            $.each(data, function(index, item) {
                $(".SubCategory" + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
                $('.SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
            });
        });
    };
});

When I check the view class names will find that drop down list for categories like : Category1, Category2 ,...etc and the Subcategory : SubCategory1, Subcategory2, ....etc hidden input values : will changed depending on the last i. Need a help to change the iteration variable depending on the selected category drop down list.

EDIT : This is the JsonResult function:

public JsonResult GetSubCatIDByCatID(int id)
    {
        db.Configuration.ProxyCreationEnabled = false;
        var subCategoryList = db.SubCategory.Where(m => m.CategoryId == id).ToList();
        return Json(subCategoryList, JsonRequestBehavior.AllowGet);
    }


When you do this:

$(".varIteration").val()

If there are multiple matching elements (and in this case there are), what do you expect the single value to be? From the description of the behavior it sounds like it's the value from the first matching element.

Get the iteration value in the event, not at the page level. So first change your event handler creation to something like this:

$(document).on("change", "[class^=Category]", function(event) {
    //...
});

This will find all elements where class "starts with" "Category", regardless of what the rest of the class name is.

Then, inside that event handler, you can dynamically navigate the DOM to find the specific iteration value you want. For the HTML you show, that would look something like this:

var iteration = $(this).closest("td").find(".varIteration").val();

Which basically means:

Starting from the element which raised the change event, navigate up the DOM to the first <td> element, then within that element find any matching .varIteration elements.

Since within that scope there's only one .varIteration element, it'll have the value you're looking for.

You'll still need to adjust the call to getSubCat(), since that also tries to use that one value. It's not clear to me what that function is supposed to actually do, so there's only so much I can advise on that. If it does need to be called for each possible value of iteration then you could perhaps put that range of values in a variable somewhere and call getSubCat() in a loop. Though a loop of AJAX calls to the same resource seems pretty inefficient. I suspect there's a better way to do whatever it is you're trying to do with that function.

But at least for the problems you describe in your comments above:

iteration variable always equal 1

That's because you only ever get one value for it, and it's the first matching value.

Nothings happen when click on any other drop down list

That's because you only ever create a change handler for that one matching value.

Create a single change handler for all matching elements and dynamically get the value you need in that change handler instead.