Search code examples
javascriptc#htmlformsdefault

Set default value of input field with read-only attribute


I have a form that posts persistent data to an SQL database. In my form I have an input field that is at first set to read-only, unless the user selects an option:

enter image description here

My problem is that if the user chooses not to enter a value in the input field, I receive this error:

enter image description here

I tried setting the default value of the input in my javascript, but i receive the same error.

$("#lejeperiode").val(" ");

It doesn't matter whether an empty string or null is inserted into the DB. This is my input field:

<input id="periodeInput" class="form-control" type="text" name="lejeperiode" value="@(Request.Form["lejeperiode"] != null ? Request.Form["lejeperiode"].ToString() : "")"/>

Solution

  • Modify your code to check if string is empty if so "" will be your default else POST value.

    cmd.Parameters.AddWithValue("@lejeperiode", string.IsNullOrEmpty(Request.Form["lejeperiode"]) ? "" : Request.Form["lejeperiode"].ToString())