Store live text field group in their respective index

I am working on a project that involves creating dynamic description textareas based on the value selected from a dropdown list. The dropdown list contains numbers 1 through 5, and for each number chosen, I need to generate corresponding textareas with series numbers increasing accordingly. For example, if the user selects 3 from the dropdown, I should create textareas for 5001, 5002, and 5003. This task is part of an MVC partial view utilizing Html.BeginCollectionItem within an Html.BeginForm on the main page. Below is the HTML snippet for reference:

<label>Amount: </label> @Html.DropDownListFor(x => x.SelectedValue, Model.vCount)

//this needs to be dynamic for how ever many numbers I'm generating
<div class="label-wrapper"> 
    @Html.LabelFor(model => model.Description)
    @Html.TextAreaFor(model => model.Description)

Edit:

I have made some progress with adding more descriptions in the view model, but I am facing challenges regarding parent divs and select elements having duplicate IDs or handling individual divs and selects with dynamic IDs. Since the partial view can be duplicated multiple times, it becomes complicated to manage which inputs to show or hide when the selects are identical. Everything works correctly when there's only one dvGenPart, but issues arise when adding another. Here's the current implementation:

<div id="dvGenPart" title="Generate Drawing #" style="height:300px;">
<br />
<br />
    <label style="width:120px;">Series:</label> @Html.DropDownListFor(m => m.SeriesNumber_id, Model.vSeries, "-- Select Series --") <label>Amount: </label> @Html.DropDownListFor(x => x.SelectedValue, Model.vCount, new { @id="ddlSelectedValue"})
    <br />
<div class="label-wrapper" id="dvDescription1">
    @Html.LabelFor(model => model.Description1)
    @Html.TextAreaFor(model => model.Description1)
    <br />
</div>
<div class="label-wrapper" id="dvDescription2" style="display:none">
    @Html.LabelFor(model => model.Description2)
    @Html.TextAreaFor(model => model.Description2)
    <br />
</div>
<div class="label-wrapper" id="dvDescription3" style="display:none">
    @Html.LabelFor(model => model.Description3)
    @Html.TextAreaFor(model => model.Description3)
    <br />
</div>
<div class="label-wrapper" id="dvDescription4" style="display:none">
    @Html.LabelFor(model => model.Description4)
    @Html.TextAreaFor(model => model.Description4)
    <br />
</div>
<div class="label-wrapper" id="dvDescription5" style="display:none">
    @Html.LabelFor(model => model.Description5)
    @Html.TextAreaFor(model => model.Description5)
    <br />
</div>

My JavaScript code:

$(document).on("change", "#ddlSelectedValue", function () {
    var vSelectedVal = parseInt($("select").val());

    switch (vSelectedVal) {
        case 1:
            $("#dvDescription2").hide();
            $("#dvDescription3").hide();
            $("#dvDescription4").hide();
            $("#dvDescription5").hide();
            break;
        case 2:
            $("#dvDescription2").show();
            $("#dvDescription3").hide();
            $("#dvDescription4").hide();
            $("#dvDescription5").hide();
            break;
        case 3:
            $("#dvDescription2").show();
            $("#dvDescription3").show();
            $("#dvDescription4").hide();
            $("#dvDescription5").hide();
            break;
        case 4:
            $("#dvDescription2").show();
            $("#dvDescription3").show();
            $("#dvDescription4").show();
            $("#dvDescription5").hide();
            break;
        case 5:
            $("#dvDescription2").show();
            $("#dvDescription3").show();
            $("#dvDescription4").show();
            $("#dvDescription5").show();
            break;
    }

});

https://i.sstatic.net/d09ck.png

Here is how the same partial view gets loaded:

<div id="dvDrawNumPost">
@using (Html.BeginForm("NewDrawingNum", "Home", FormMethod.Get, new { id = "genDrawForm", @class = "english-form", enctype = "multipart/form-data" }))
{
    <div id="dlgGenDraw">
        <div id="dvNewDraw" style="clear:both;">
            @for (int i = 0; i < @Model.NewDrawNums.Count(); i++)
            {

                @Html.EditorFor(model => @Model.NewDrawNums[i])
            }
        </div>
        <br />

        @Ajax.ActionLink("Add Drawing #", "CreateNewDrawNum", null, new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "dvNewDraw" }, new { @class = "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only AddDrawbtn" })

        <br />
        <br />
        <input type="submit" id="btnSubmitNewDraw" name="submit" value="Save" />
    </div>
}

Answer №1

The user's choice of fields is done on the client side, so the creation of textareas should also happen there unless you prefer an intermediate step. Essentially, you can have the user select a number and submit it. Then, the server can return a new page with that specified number of textareas. However, I assume that's not your desired approach.

Therefore, since this functionality needs to be implemented on the client side, you will need to bind to the dropdown's change event and use JavaScript to generate the textareas:

$('#SelectedValue').on('change', function () {
    var numberOfTextareas = $(this).val();
    // code to create textareas
});

The method for generating the textareas is entirely up to you. You could manually create the elements using JavaScript and insert them into the DOM, send an AJAX request to a server endpoint that returns a partial view containing the required textareas based on the given number, or utilize frameworks like Knockout or Angular to handle the generation process using a predefined template.

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

error detection in AJAX response handler

My web-application was created using PHP, AJAX, and jQuery, and the development process went smoothly. The majority of the requests to the application are made via AJAX for operations such as insert, update, delete, and select. I have already implemented ...

When using VSCode for Next.js projects, automatic imports from "react" are not supported

* While similar, this question is not a duplicate of this other question; the solutions provided there are tailored for TypeScript and do not seem to apply to JavaScript. In my current project using Next.js in Visual Studio Code, I am facing an issue wher ...

Utilizing the require function to implement an AngularJS Controller without having

I've been working with requireJS in my application. Every time I try to register a controller on my module, it gives me an error saying that the controller is not defined. Here's the code for my LoginController located in login.controller.js: f ...

Exploring the integration of react-leaflet with Nextjs: A step-by-step guide

Hello everyone, I'm currently facing an issue while trying to integrate a Leaflet map into my Next.js application. The error window is not defined keeps popping up and despite searching on stackoverflow, I haven't found a solution yet. The code ...

Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below. <template> <div> <Hero /> <Homebooks :details="details" /> </div> </template> <s ...

Retrieve the most recent version of the document stored in MongoDB

Is there a way to retrieve the _id (the Mongo ObjectID) of an updated document without having to find it by newData/oldData? I attempted the following: ... collection.update(oldData, newData, function(err, doc) { console.log(docs); // This prints "1" ...

The A-Frame buffer geometry merger may cause unexpected entity shifts under certain circumstances

My A-Frame scene has a simple issue with the buffer-geometry-merger component. It works perfectly fine when entities are written in static HTML, but not when injected into the DOM using an A-Frame component. It seems like the geometry gets shifted, as if t ...

What is the best way to pass value to a URL in a React JS application?

Is there a way to properly use history.push in React to push text to the URL route manually? I am trying to achieve this in my onChange method for an input field: function Header(props) { return ( <div> <input type="radio" onChan ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

What is the process for generating a watermark directive in angularjs?

My application utilizes a jQuery script for watermarking textboxes. I created a directive to easily apply this watermark to input elements, but it's not functioning as expected. While debugging, I can see the watermark being added, but once the UI fin ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

What is the process for invoking an Express route using Ajax?

I encountered a problem with calling an Express route in my Node.js application using Ajax when submitting a form. Here is the code for my route: router.post("/user", function(req, res) { console.log("FORM DATA: " + JSON.stringify(req.body)); res ...

Developing a new React application with Access Control List (ACL) and encountering an issue with Casl

I've recently started working with casl and it feels like I might be overlooking something crucial. So, I created a file named can.js which closely resembles the example provided in the documentation: import { createContext } from 'react'; i ...

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

What causes an "Internal Server Error" when attempting to use data for a database request with AJAX GET/POST in Laravel?

There's a unique issue that I'm struggling to resolve... Every time I drag and drop an event into the calendar, an Ajax Post Request is sent to my controller. The controller then inserts some data into the database with the event name received v ...

Perform Function Again

Recently, I came across some code for a tesseract ocr from Google that seemed to be functioning well. However, I encountered an issue where it would work fine the first time I input a URL, but on the second run, it wouldn't work without a manual page ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

Tips for aligning meshes to the left and ensuring responsiveness in three.js

Currently working on a website using three.js, I'm facing an issue where I can't seem to align and make the mesh responsive simultaneously. My current approach to alignment is: cube.position.x = -20 However, when I try resizing the window, the m ...

Unraveling the mysteries of this PHP-generated object

Need help with iterating over a JSON object generated by PHP code in response to a web service request. Looking for guidance on rendering sub-objects in a select list, especially those with value indexes. Can someone provide assistance on populating a sel ...

Is there a built-in method or library for extracting data from JSON strings in programming languages?

Duplicate Query: how to parse json in javascript The data sent back by my server is in JSON format, but it doesn't follow the usual key/value pairs structure. Here's an example of the data I'm receiving: ["Value1","Value2","Value3"] ...