A guide on expanding an HTML table dynamically with MVC razor syntax

My goal is to dynamically add new rows to a table by following the advice given in this answer on Stack Overflow: Add table row in jQuery

I have successfully implemented it for one of my table requirements as seen below:

    function onAddItem() {
    $('#myDynamicTable tr:last').after('<tr><td style="width: 78%;" class="itemName"><input type="text" style="width: 97%;" /></td><td style="width: 20%;" class="itemQty"><input type="text" style="width: 87%;" /></td></tr>');
    $("#myDynamicTable").show();
}

Now, I'm attempting to apply the same concept to the following <tr>..</tr> structure but encountering issues.

<tr class="tdBorder">
                    <td class="tdBorder">
                        @Html.TextBox("Id", null, new { @width = 60 })
                    </td>
                    <td>
                        @Html.TextBox("Name", null, new { @width = 150 })
                    </td>
                    <td>
                        @Html.DropDownList("ddlCountries", new SelectList(ViewBag.CountryList as System.Collections.IEnumerable, "Value", "Text"), new { @width = 60 })
                    </td>
                    <td>
                        @Html.TextBox("Event", null, new { @width = 60 })
                    </td>
                    <td>
                        @Html.DropDownList("ddlRegions", new SelectList(ViewBag.RegionList as System.Collections.IEnumerable, "Value", "Text"), new { @width = "auto" })
                    </td>
                    <td>
                        @Html.TextBox("Remarks", null, new { @width = 700 })
                    </td>
                </tr>

I attempted the line below, however, it caused issues with jQuery:

$('#myDynamicTable tr:last').after('<tr class="tdBorder"><td class="tdBorder">@Html.TextBox("Id", null, new { @width = 60 })</td><td>@Html.TextBox("Name", null, new { @width = 150 })</td><td>@Html.DropDownList("ddlCountries", new SelectList(ViewBag.CountryList as System.Collections.IEnumerable, "Value", "Text"), new { @width = 60 })</td><td>@Html.TextBox("Event", null, new { @width = 60 })</td><td>@Html.DropDownList("ddlRegions"...

Answer №1

It has been mentioned in the comments that you cannot use Razor HTML helpers in a separate JavaScript file. You have two options in this scenario:

One option is to utilize page-specific JavaScript within a <script> tag in your Razor view. Any helpers used will render similarly, and your current code should function properly.

Alternatively, you can render the list in the view and then copy it as needed in your JavaScript code.

For example:

// Your regular view markup here

<div id='countries' style='display:none'>
    @Html.DropDownList("ddlCountries", new SelectList(ViewBag.CountryList as System.Collections.IEnumerable, "Value", "Text"), new { @width = 60 })
</div>
<div id='regions'>
    @Html.DropDownList("ddlRegions", new SelectList(ViewBag.RegionList as System.Collections.IEnumerable, "Value", "Text"), new { @width = "auto" })
</div>

The JavaScript code could look something like this:

var countries = $('#countries').html();
var regions = $('#regions').html();
var html = '<tr class="tdBorder">'
        + '<td class="tdBorder"><input name="Id", type="text" /></td>'
        + '<td><input name="Name" type="text" /></td>'
        + '<td>' + countries + '</td>'
        + '<td>input name="Event" type="text" /></td>'
        + '<td>' + regions +'</td>'
        + '<td><input name="Remarks" type="text" /></td></tr>'

$('#myDynamicTable tr:last').after(html);

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

Convert an array of objects into an object where the keys are determined by the value of a specific

I'm working with an array that looks like this: const inventory = [ { fruit: 'apple', quality: 'good', quantity: 10 }, { fruit: 'banana', quality: 'average', quantity: 5 }, { fruit: 'orange', qua ...

Non-functioning Tooltips on Google Charts

Currently, I am working on integrating Google Chart with ASP.NET and linking it to a SQL Server database. I have encountered an issue while attempting to customize the tool tip. Below is the Header Code: <script src="js/jquery/jquery-1.10.2.js" type=" ...

aligning divs in a horizontal distribution is ineffective when the divs become fixed in place

When distributing divs horizontally equally, issues arise when these elements are attached without spaces in between (particularly in Chrome and Firefox). For instance: http://jsfiddle.net/pdelorme/au9ouko0/ HTML : <div class="ul"> <div class=" ...

Modifying the dimensions of mat-card in Angular Material

https://i.stack.imgur.com/CP16N.png I am struggling to make both components the same height, similar to the left form. I have tried adjusting margins and padding but nothing seems to work. Below is the HTML code for the parent element: <mat-tab label= ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Fixed header in a div, allowing content to scroll when hovering over the header

How can I ensure that the header remains fixed at the top while allowing the content to scroll when hovered over? The current issue is that when a user hovers over the header and tries to scroll, the content does not move. body { margin: 0; ...

Setting up flowplayer for multiple div elements: a tutorial

I have a collection of videos and I am trying to set up the player for each div that holds a video. When constructing the divs in my JavaScript code, it looks like this: <div id="player+{{$index}}"></div> // The "player" + index is generat ...

Swap the image when hovering over it

Is it possible to modify this specific code so that a hover effect is triggered on mouseover? I attempted to look into similar questions and answers, but I found them difficult to understand. Here is the HTML snippet: <a href="RR.html"><img src ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

When utilizing a node.js TCP socket to receive and send modified data, the functionality only operates successfully on the initial attempt

I am attempting to create a node.js TCP socket that will receive data, modify it, and then send it back. I found a helpful example on Stack Overflow here: . The example works perfectly as is, but when I add my own code to send data back, it only works for ...

Discovering if a div element has children using Selenium IDE

As I begin to automate testing for our website with Selenium IDE, I must admit that I am still learning the ins and outs of it. We utilize highcharts to exhibit data on our site. The challenge arises from the fact that there are 3 div elements handling th ...

grab the content from a text editor and insert it into a div element

Currently, I am trying to extract text from my content editable div and place it in another div (similar to the one seen on stack overflow). However, I am encountering a frustrating issue. 1. My content div seems to be lagging behind. When I type in my ed ...

Vue and Nuxt: Concealing a Variable in .env File Post-Build

     Within my Nuxtjs project, I have implemented a process in which I encrypt requests before they are sent to my Laravel API. Once the response is received, I decrypt it using specific global functions that have been defined... function encryptDataLa ...

Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here $(document).ready(f ...

Error Alert: JQuery Pop Up Issue

Struggling with getting my JQuery Pop-Up Box to work properly. Any guidance for a newbie like me on how to fix it would be greatly appreciated. Here's the code I've been working on: <!-- POP UP HTML --> <div class="infocontainer"> ...

how can I transfer model values to a dashboard in Rails 5?

I have developed an app that includes an adminlte dashboard. The dashboard is populated with various values obtained by a jQuery file. I am trying to pass module values to the dashboard. For example, the number of users shown in the dashboard should be fet ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...

I am facing difficulties when trying to map the data using react js/axios

After removing the map function from the code, I encountered an error stating that map is not a function. Can someone please assist me with this issue? Here is the updated code: const [text, setText] = useState([]); const axios = require('axios&ap ...

Error encountered in React: When a parent component tries to pass data to a child

I have a Quiz object that I need to pass a single element of (questionAnswerPair) to a child component called QuestionAnswer. Although the Quiz data is fetched successfully and iterated through properly, there seems to be an issue with passing the Questio ...

Discover data using JavaScript recursively through paths

Here is the data structure I am working with: [ { name: 'root', children: [ { name: 'page', children: [ // and so on ] } ] } ] I am in need of a function that can retrieve ...