Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using:

function tblnewrow() {

    var newrow = '<tr>' +
     '<td><span class="edit-mode"><input type="text" class="form-control edit-mode" id="particular" placeholder="Enter Particular"/></span></td>' +
     '<td><span class="edit-mode"><input type="text" class="form-control edit-mode" id="acctcode" placeholder="Enter Account Code" /></span></td>' +
     '<td><span class="edit-mode"><input type="text" class="form-control edit-mode" id="ppmpcode" placeholder="Enter PPMP Code" /></span></td>' +
     '<td><span class="edit-mode">@Html.DropDownList("Account Code", (SelectList)ViewBag.listValues, "---Select Account Code---", new { @class = "form-control edit-mode", id = "acctcode" })</span></td>' +
     '<td align="center"><button class="btn btn-success edit-mode" id="saveParticular" type="submit">Save</button><button class="btn btn-danger cancel-add edit-mode">Cancel</button></td>'

    $('#particularTbl tr:last').after(newrow);
};

I have successfully added a new row, but I'm encountering an issue when adding a dropdown list - it doesn't seem to be functioning correctly. Can anyone point out what might be wrong here? Thank you in advance!

Answer №1

If you try to use server helpers in JQ and expect it to render correctly on the client side, it will not work as expected. You must replace

'<td><span class="edit-mode">@Html.DropDownList("Account Code", (SelectList)ViewBag.listValues, "---Select Account Code---", new { @class = "form-control edit-mode", id = "acctcode" })</span></td>'

with pure HTML code like

'<td><span class="edit-mode"><select class="form-control edit-mode" id="acctcode"><option value='1'>---Select Account Code---</option></select></span></td>'

For the option list, you can pass values from ViewBag to JQ like this:

var bag = "<%= ViewBag.listValues%>"

Then you will need to build your option list from that.

Answer №2

Consider utilizing .ToHtmlString()

@Html.DropDownList("Account Code", (SelectList)ViewBag.listValues, "---Choose Account Code---", new { @class = "form-control edit-mode", id = "acctcode" }).ToHtmlString()

Answer №3

I experimented with a similar approach to yours. Here is my code -

<div id="div"></div>

<script>

    window.onload = function(){
        var sel = '@Html.DropDownList("List")';
        document.getElementById("div").innerHTML = sel;
    };

</script>

Upon viewing the page source, I noticed -

<div id="div"></div>

<script>

    window.onload = function(){
        var sel = '<select id="List" name="List"><option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>';
        document.getElementById("div").innerHTML = sel;
    };

</script>

The issue arises from the line breaks in the generated select list, causing an error in JavaScript -

Uncaught SyntaxError: Unexpected token ILLEGAL

It seems like you are facing a similar problem.

If your browser supports ECMAScript6 (such as the latest version of Chrome), you can use backticks to resolve this issue. It worked for me.

var sel = `@Html.DropDownList("List")`;

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

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Collecting Images Based on Quantity

Despite using async to download URIs on every request and closing when a certain count is reached, I am still encountering the issue of files not being downloaded properly and exiting before reaching their maximum. Can someone suggest the best solution t ...

Tips for creating a form-flip, similar to a card-flip effect, using web technologies

Looking to create a card flip effect similar to the one shown here. Once the sign up process is finished, the card will smoothly flip over to reveal the other side with a transitioning effect. ...

Array-based input validation

Is there a way to validate an input field against a list of strings in an array without using custom directives or patterns? For example, if the array contains town, city, and house, then typing any of those words should result in a validation failure. An ...

Creating a unique custom bottom position for the popover and ensuring it is fixed while allowing it to expand

Creating a customized popover similar to Bootstrap's popover, I have successfully implemented popovers in all directions except for the top direction. My challenge lies in fixing the popover at the bottom just above the button that triggers it, and en ...

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

How to Click a Button Using Selenium without Specifying ClassName or ID

I am working on a project related to Browser Automation, but I'm encountering issues with clicking a specific button. I attempted the following steps: webDriver.FindElement(By.XPath("//*[@id='uploadForm: fileup']/div[1]/button[1]")).Click() ...

Element enclosed within a territory of mongoose Schema

In the midst of developing an API that provides detailed information about laptops, I am utilizing Node.js and MongoDB with Mongoose. The schema I am working with is as follows: const productSchema = mongoose.Schema( { name: { type: String, ...

The following error occurred: Next Auth TypeError: URL is not valid

Every time I run my Nextjs project, I keep encountering an issue related to Next Auth. Despite using version 4.3.1, I am unsure about how to resolve it. Any assistance with next-auth would be greatly appreciated. Although I attempted to update my next-aut ...

There are three pop-up windows displayed on the screen. When each one is clicked, they open as intended, but the information inside does not

Every button triggers a unique modal window Encountering an unusual problem with Bootstrap 5 modal functionality. Within a webpage displaying a list of database entries (refer to the screenshot), each entry features three buttons to open corresponding mod ...

Measuring Internet speed using Node.js

Is there a way to measure internet speed in server-side node.js? I am currently sending the current timestamp from the client side while making an http request. Client side code: var image = document.createElement("img"); image.width = 1; i ...

JavaScript: How can I execute a count that pertains solely to elements that are currently visible

Using jQuery, I have implemented a search functionality that hides items in a list that do not match a given string. The code loops through a list of divs and utilizes $(this).fadeOut(); to hide the elements. While this functionality works effectively, I ...

I'm encountering an issue with this error message: "Warning: Each item in a list must be assigned a unique 'key' prop."

I encountered an error message... Warning: Each child in a list should have a unique "key" prop. I'm puzzled about this because I believe I have assigned a unique key for my map. All the resources I've checked regarding this warning are relat ...

Ensuring that only one field is selected with mandatory values using Joi validation

Is there a way to create a validation rule utilizing Joi that ensures if valueA is empty, then valueB must have a value, and vice versa? My current approach involves using Joi for validating an array of objects with properties valueA and valueB. Below is ...

What's the best way to showcase data in a column dynamically depending on its specific columns?

I have an array of objects representing columns and another array representing table data. I need to dynamically display the data in the specified columns. Some objects have 3 key-values which should be displayed in specific columns. The second object in ...

Prevent Buttons from Being Clicked While Another is Active in Angular

I am facing a challenge with my Angular functions that enable search features. My goal is to allow only one feature to be selected at a time. /* Trauma Search functionality */ $scope.traumaSearch = false; $scope.traumaText = "Trauma Center"; $scope.togg ...

Top tips for writing JavaScript that incorporates an AJAX call to determine whether the default action should be blocked

Utilizing JavaScript and jQuery, I am developing a handler for form submission that will either allow or prevent the form from being submitted based on certain conditions. Although this task is fairly straightforward, it becomes more complex due to the ne ...

Tips for navigating to an external website through GraphQL

I am currently utilizing Node.js and Front-end on Next.js. I have a GraphQL server with a GetUrl method that returns a link (for example: ""). My goal is to redirect a client who made a request to that page with a Basic Auth Header. From what I understan ...

Methods for removing cookie during logout with Express and Passport JS?

I have been struggling to delete cookies upon logout but haven't had any luck so far. I searched online and came across two methods: Setting a new expiration date for the cookie res.cookie('connect.sid', '', {expires: new Date(1 ...

A more efficient method for passing a function as an argument using the keyword "this"

When it comes to passing a function as an argument that uses the this keyword, is there a preferred method or correct way to do so? An example would be helpful in understanding this concept better: For instance, if I want to fade out an object and then r ...