Ad

How To Change Html Input Type Based On Another Text Box Value MVC?

I went through similar questions but still unable to figure out.

I have a form as shown below. One of the input type is a hidden. The values for both textboxes are specified by the model passed from the controller.

 <form asp-action="Edit">
     //input one
     <div class="form-group" id="control1">
            <label asp-for="Value" class="control-label"></label>
            <input asp-for="Value" class="form-control" required="required" id="param2" />
            <span asp-validation-for="Value" class="text-danger"></span>
     </div>
     <input type="hidden" asp-for="Type" id="param1" />
 </form>

The default input type is textbox, but suppose if the value of asp-for="Type" is equal to "drop", I want to change the input type to dropdown list with True or False Option. I have tried the following. I added the new form group and assigned id=control2.

       <div class="form-group" id="control2">
            <select asp-for="Value">
                <option value="True">True</option>
                <option value="False">False</option>
            </select>
        </div>

What I did was that, I select the value of param1 using jquery and if it is equal to "bool" then I hide control1 and show control2 (which is wrong). So even though I have selected the value using the dropdownlist from control 2, the textbox value from control1 (which I hide) is being used when POST occurred.

Can someone please advise me on this? Either an alternative method or continue using my method by to use the value of control2

Many thanks in advance!

Ad

Answer

Instead of using jQuery you can use the razor syntax to add or remove the element from DOM. Update your code as below.

<form asp-action="Edit">
     //input one
	 
	 <input type="hidden" asp-for="Type" id="param1" />
	 @if(Model.Type.Equals("Drop"))
	 {
		 <div class="form-group" id="control2">
            <select asp-for="Value">
                <option value="True">True</option>
                <option value="False">False</option>
            </select>
		</div>
	 }
	 else
	 {
		<div class="form-group" id="control1">
            <label asp-for="Value" class="control-label"></label>
            <input asp-for="Value" class="form-control" required="required" id="param2" />
            <span asp-validation-for="Value" class="text-danger"></span>
		</div>
	 }
     
 </form>

Here if condition is true it will add drop down in DOM else it will append texbox.

Hope it helps.

Ad
source: stackoverflow.com
Ad