0

I have a drop down list and a input field on the page using MVC. I use JQuery to get the value from Controller to set value for this input field depends on the drop down list selection. I noticed the input field is populated on the page, but the value attribute is still empty checked using browser Developer Tool. I use

 @Html.EditorFor(model => model.inputFieldID, new { htmlAttributes = new { @id = "inputFieldID"} })

In JQuery ajax I set the value like:

$("#inputFieldID").val(NewValueFromDB);

and I can see value is set using

alert($("#inputFieldID").val());

but on the page, the value attribute field is empty, what did I miss?

UPDATE:

I figured out that because I try to make the input field not editable, so I gave @disabled = "disabled" to it. That seems stopping the value get passed to Controller.

But my question is, if I want to make the input field not editable, but still can pass the value to Controller what should I do?

ANSWER Use readonly instead of disabled attribute and give a grey background-color to make it look like not editable.

Thank you.

Xiao Han
  • 1,004
  • 7
  • 16
  • 33

1 Answers1

1

The jQuery .val() method updates the element's value property and not the attribute value.

The attribute is mainly used to initialize the property.

Normally you do not have a need for the value attribute of input elements.

See Properties and Attributes in HTML

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Thanks, I figured out that because I try to make the input field not editable, so I gave @disabled = "disabled" to it. That seems stopping the value get passed to Controller. – Xiao Han Sep 28 '17 at 19:50
  • @XiaoHan to make it not editable use the `readonly` attribute. – Gabriele Petrioli Sep 28 '17 at 19:53
  • Thank you, it seems I have to use readonly and apply some background-color style to the input field to make it looks like not editable. – Xiao Han Sep 28 '17 at 20:00