6

I want to set the value of my input text using jquery. I have tried by doing this :

    <div class="editor-label">
        @Html.LabelFor(model => model.ID )
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ID)
        @Html.ValidationMessageFor(model => model.ID)
    </div>

and jquery syntax :

    $("#ID").val(data.ID);

But it is not working. I have tried the same jquery code with this :

<input type="text" id="ID" />

This approach is working , but I don't know why @Html.EditorFor is not working with jquery .Thanks in advance

Hammad Shahid
  • 2,216
  • 5
  • 32
  • 60

5 Answers5

4

You're better off using the TextBoxFor method as it allows you to change the id and class of the element directly whereas EditorFor doesn't unless you create a custom edit state for it (using EditorTemplate).

@Html.TextBoxFor(model => model.ID, new { id = "ID" })

I believe @Html.EditorFor(model => model.ID) will set the name attribute as that is what mvc depends upon to do its model binding so if the above is not to your liking you can perhaps use the name as a selector.

JonVD
  • 4,258
  • 24
  • 24
3

You can add the @id, @class, etc on EditorFor as follows:

@Html.EditorFor(model => model.ID, new {htmlAttributes = new {@id="someid"}})
Sum None
  • 2,164
  • 3
  • 27
  • 32
d2z2
  • 31
  • 1
2

this works for me

<div class="editor-field">
    @Html.EditorFor(model => model.ID)
    @Html.ValidationMessageFor(model => model.ID)
</div>

<div class="editor-field">
    @Html.EditorFor(model => model.SetID)
    @Html.ValidationMessageFor(model => model.SetID)
</div>

and javascript is

var d = $("#ID ").val();
$("#SetID").val(d);  

or

$("#SetID").val($("#ID ").val());
0

You should use

@Html.EditorFor(model => model.ID, new {@id="someid"})

Then

$("#someid").val (someval)
AlexB
  • 7,302
  • 12
  • 56
  • 74
StringBuilder
  • 1,619
  • 4
  • 32
  • 52
  • I don't think you can do this as the second parameter of the EditorFor actually takes View data and not an anonymous object containing html attributes like TextBoxFor does. See http://stackoverflow.com/questions/3735400/html-attributes-for-editorfor-in-asp-net-mvc for more details. – JonVD Jun 27 '13 at 05:24
  • Maybe you right , I am from mobile so I cant check, but I think one of the params should be ... – StringBuilder Jun 27 '13 at 05:34
  • I was surprised that you couldn't set html attributes on EditorFor too, seems like a strange decision to make. – JonVD Jun 27 '13 at 05:49
0

Try this

$("#someid").prop('checked', true); // for checked
$("#someid").prop('checked', false);
danteMesquita
  • 87
  • 1
  • 7