gurehbgui
gurehbgui

Reputation: 14694

jquery not working within the view of a asp.net mvc3?

i have a problem with my asp.net mvc3 page. i have a view which has a form in it to create a item of a specific model. it looks likt this:

@model testPro.Models.AddItemModel
@{
    ViewBag.Title = "New";
}
@*<h2>New</h2>*@

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>New Item</legend>

                <div class="editor-label">
                    @Html.LabelFor(model => model.UserItem.name)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.UserItem.name)
                    @Html.ValidationMessageFor(model => model.UserItem.name)
                </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script>
    $(document).ready(function () {

        alert("test");
        $("#UserItem_Name").html("bla");
        $("#UserItem_Name").attr('disabled');
    });
</script>

at the end i have my jquery stuff which should change the text-box.

the problem is, nothing is changing and i dont know why

and yes: i have jquery included in the header.

Upvotes: 0

Views: 216

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

Try:

<script type="text/javascript">
    $("#UserItem_name").val('bla');
    $("#UserItem_name").attr('disabled', 'disabled');
</script>

Things to notice:

  • Your textbox id is UserItem_name, not UserItem_Name which obviously is not the same thing
  • Use .val() to set values of form input fields instead of .html()
  • The .attr() method takes 2 arguments when you want to set an attribute value: 1) the attribute name and 2) the attribute value. You are currently passing only one parameter, so you are basically reading the attribute value, not setting it.

Also if this code is inside a partial view that you have injected into your DOM after an AJAX request, you should remove the $(document).ready handler.

Upvotes: 1

Related Questions