Choosing a value from the dropdown menu will reveal a textbox, but it does not retain the value that was entered into it

In my perspective, I have

        <div class="col-md-3 ">
            @{
                List<SelectListItem> deformitylevel = new List<SelectListItem>();
                deformitylevel.Add(new SelectListItem { Value = "hip", Text = "Hip" });
                deformitylevel.Add(new SelectListItem { Value = "knee", Text = "Knee" });
                deformitylevel.Add(new SelectListItem { Value = "ankle", Text = "Ankle" });
                deformitylevel.Add(new SelectListItem { Value = "other", Text = "Other" });
            }
                @Html.DropDownListFor(model => model.DeformityLevel, deformitylevel, "--Choose Level -", new { @class = "form-control", @onchange = "showdeformitytextbox()", id = "deformitydropdown" })
                @Html.ValidationMessageFor(model => model.DeformityLevel, "", new { @class = "text-danger" })
        </div>
        <div class="col-md-3">
            @Html.EditorFor(model => model.DeformityLevel, new { htmlattributes = new { @class = "form-control", id = "deformitytextbox" ,style= "display:none"} })
        </div>

The function that guides me is

function showdeformitytextbox() {
        if ($("#deformitydropdown option:selected").text() == 'Other') {
            $("#deformitytextbox").show();

        }
        else {
            $("#deformitytextbox").hide();
        }
    }

Upon selecting "Other" in the dropdown list, instead of saving the input value from @Html.EditorFor, it saves 'other' in the database.

I am missing something crucial, any guidance?

Answer №1

To streamline this process, it's recommended to separate the model fields for the drop-down and the text box. While the code below may work, it could create extra work if you need to go back to the page with a different value selected. However, the following code correctly submits the expected value in the text box. The key idea is to disable the drop-down as you submit.

If your form has an id of submitForm set up like this:

@using (Html.BeginForm("someActionName", "someControllerName", FormMethod.Post, new { @id="submitForm"}))

Then the code below will prevent the drop-down from submitting its value during form submission:

   $("#submitForm").submit(function () {
      if ($("#deformitydropdown option:selected").text() === "Other") {
         $("#deformitydropdown").attr("disabled", true);
      } else {
         $("#deformitydropdown").removeAttr("disabled");
      }
   });

Answer №2

To enhance the functionality, I suggest renaming your current controls and adding a hidden form element for DeformityLevel. Then use JavaScript to update its value based on events from DropdownList and text box.

***Here is an example (jq not verified, for demonstration purposes only)

<select id="DeformityLevel_DDL">
        <option></option>
        <option></option>
        <option></option>
    </select>
    <input type="text" id="DeformityLevel_TB" />
    <input type="hidden" id="DeformityLevel" name="DeformityLevel" />
    <script>
        $(document).ready(function () {
            $('#DeformityLevel_DDL').change(function () {
                if ($(this).val() != 'other') {
                    $('#DeformityLevel').val(this.val());
                }
            });

            $('#DeformityLevel_TB').on('change', function () {
                $('#DeformityLevel').val($(this).val());
            });
        });
    </script>

Answer №3

It appears that your function is specifically designed to show the input in #deformitytextbox and update the model property when the value entered changes. To ensure this functions properly, consider updating the model property when changes occur. If the form automatically submits upon selecting a change, it may be necessary to utilize preventDefault.

Answer №4

Don't forget to give TextBox a try, but make sure your htmlAttributes parameter is correct this time. Here's the corrected version:

<div class="col-md-3 ">
    @Html.DropDownList("DeformityLevel", deformitylevel, "--Select Level -", new { @class = "form-control", @onchange = "showdeformitytextbox()", id = "deformitydropdown" })
    @Html.ValidationMessage("DeformityLevel", "", new { @class = "text-danger" })
</div>

<div class="col-md-3">
    @Html.TextBox("DeformityLevel", null, new { @class = "form-control", id = "deformitytextbox", style = "display:none;" })
</div> 

<script>
    function showdeformitytextbox() {
        if ($("#deformitydropdown option:selected").text() == 'Other') {
            $("#deformitytextbox").show();
        } else {
            $("#deformitytextbox").hide();
        }
    }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manage Python code using HTML code

Greetings! I am currently working on a Robot control system and would like to be able to control it through a website that I have created. However, I am facing difficulties in connecting this to Python code to control the Raspberry Pi GPIO. You can access ...

Making AJAX requests repeatedly within a loop

My current challenge involves implementing multiple ajax requests within a loop to populate several dropdown lists. Running the requests sequentially has resulted in only the last item in the loop being populated with values. var targetcontrols = []; ...

Getting the inner element of a particular child from the parent div using selenium with javascript

<div class="A"> <svg> ... </svg> <button> <svg> ... </svg> </button> <svg> ... </svg> </div> <div class="A"> <svg> ... </svg> <button> ...

"Looking to dynamically adjust attributes within a popover using JavaScript in Bootstrap 5? Let me show you how

I have been attempting to utilize JavaScript to set an HTML attribute in a popover within Bootstrap 5, but I am encountering difficulties. Below is the code snippet for the popover: <button type="button" class="btn btn-secondary mx-3&quo ...

JavaScript: protecting data, revealing functionality

Looking to enhance my understanding of Javascript basics in order to delve into client-side frameworks like Knockout and Angular, as well as make headway in learning Node.js. I've selected a simple problem used in teaching C# and am now attempting to ...

Using the googleapis library within HTML is not permitted

I have been attempting to execute a simple function (uploadFile(test.txt)) within an HTML file, but I am encountering issues as my app.js and Google APIs are not being recognized or called. Node.js is throwing this error: Uncaught ReferenceError: uploadFi ...

Unexpected behavior from Bootstrap within React

I recently started working on a React project that I initiated with the create-react-app command. To incorporate Bootstrap into my project, I added the necessary CDNs to the public/index.html file after generating the project. <link rel="stylesheet" hr ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

What could be causing my Node.js (Express) application to have a response time of 21000 milliseconds for a simple GET request?

Here is the block of code I am working with: // GET - Default (root) app.get('/', (req, res) => { console.log('GET request to "/"..'); res.header('content-type', 'text/html'); return res.end('&ap ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...

Introducing a variety of services into the system

From my understanding, services must be provided and injected, meaning each service needs to be placed inside the constructor like this: constructor (private a: AService, private B: BService) {} In my scenario, I have multiple services that all follow th ...

Execute the function once the audio has finished loading

I need help running a function once an audio file has finished downloading. This is my JavaScript code: // https://freesound.org/people/jefftbyrd/sounds/486445/ var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.m ...

Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

Angular-Breeze Navigation Strategy Template

Within my Angular site, there is a page that allows users to run reports based on various criteria such as employee ID, event ID, from date, to date, and more. Once the user selects the parameters for their report and clicks submit, they are shown search r ...

Node.js is expecting callback functions, but instead received an [object Object]

Currently, I am attempting to upload a file using node.js. router.post('/image', [ multer(), function(req, res) { var file = req.files.file; console.log(file); res.end(); }]); I am encountering an issue with the code above. Specifically, ...

Phantom.js callback Reference error experienced while optimizing Phantom.js on Node.js/Express.js to eliminate the problem of excessive callbacks

I've been working on this extensive block of code that works, but I'm looking to refactor it properly. Following the principles outlined in Callback Hell, I attempted to break it down into non-anonymous functions and separate them from the main c ...

When comparing dates in MongoDB between the frontend and backend, there is an exact match; however, the comparison still triggers

I offer a service that verifies if the date on the frontend matches exactly with the record in the backend database Here is the code snippet: if (schedule.due_date != paymentBody.user_view_before_schedule[i].due_date) { console.log(schedule.du ...

Securing user access in Angular: managing new tab or new browser window

When developing my AngularJS-based application, I initially utilized localStorage to save the JWT authentication token obtained from the backend. The app employed an interceptor to send this token along with every request made to the backend server. This p ...

Easy steps for creating unit tests in a project that utilizes RequireJS

I've been attempting to write unit tests using chai mocha, but I keep encountering the error below. ReferenceError: define is not defined The application I'm working on is written in TypeScript. Interestingly, when I create a dummy file for t ...

Obtain a URL using JavaScript's regular expressions

Is it possible to use JavaScript regex to fetch the first function parameter? For instance, when I click on a tag in this page element, how can I extract the inline link? Here's an example: <li><a href="#blog" data-rel="clos ...