When running Javascript, the code is displayed rather than being executed

I have a current MVC - C# application that generates various "popup" screens containing necessary information. I wanted to apply the same method to create a popup displaying a version history (listing the Versions with their corresponding changes).

However, every time I click on the link to view the list, the JavaScript function that is called simply displays the code of the function instead of executing it.

In my .css file, I have defined the following style (this style is used throughout the application under different names):

#VersionHistoryList
{
    position: fixed;
    width: 50%;
    height: 70%;
    top: 15%;
    left: 25%;
    padding: 1%;
    background-color: white;
    border: 1px solid #444;
    border-radius: 5px;
    z-index: 100;
    box-shadow: 0 0 0 9999px rgba(0,0,0,0.5);
    color: #f5f1ef;
    background-image: url('../images/bg.jpg');
}

In my view, I have included the following code (initially, this view only showed the current version number statically):

<div style="float: left; width: auto;">
    <span ><a style="color:White" href="javascript:toggleHistory">JPortal, version @ViewContext.Controller.GetType().Assembly.GetName().Version</a></span>
        <div id="VersionHistoryList" style="display: none;">
            <span style="font-size: larger;">Version History</span>
            <div style="height: calc(100% - 100px); overflow: auto;">
                <div class="SearchResults">
                    @foreach (JudicialPortal.Models.VersionHistory.V sr in @JudicialPortal.Models.VersionHistory.HistoryList)
                    {
                        <span style="display: block; font-weight: bold;">
                            Version @sr.Number
                        </span>
                        <span style="float: left; width: 10%;"> @sr.Date </span>
                        <span style="float: right; text-align: left; width: 90%;">@sr.Description</span>
                    }
                </div>
            </div>
            <button type="button" class="m-btn red-stripe" onclick="$('#VersionHistoryList').hide(0);" style="float: left;">
                Cancel<i class="icon-remove"></i></button>
        </div>

</div>

I have also added the following .cs files to my model files (partial code shown here):

namespace <applicationname..Models
{
    public class VersionHistory
    {

        public class V
        {
            public string Title { get; set; }
            public string Number { get; set; }
            public string Description { get; set; }
            public DateTime Date { get; set; }
        }

        public static List<V> HistoryList
        {
            get
            {
                var data = new List<V>();
                data.Add(new V() { Number = "1.0.1", Title = "Registration Setup", Date = new DateTime(2014, 7, 11), Description = "Setup For Registration." });
                data.Add(new V() { Number = "1.0.2", Title = ...

I must mention that I took inspiration for the code from an ASPX application that shows its application history.

The JavaScript function triggered by the link in the tag is:

    toggleHistory = function () {
        $('#VersionHistoryList').toggle();
        $('#VersionHistoryList').focus();
    }

However, when this JavaScript function is called, instead of displaying the popup, it displays the function's code itself.

Screenshot displaying the code

Any assistance on this matter would be greatly appreciated.

Answer №1

Strive to keep your javascript unobtrusive by following these steps:

First, add a class to your links:

<span ><a style="color:White" class="toggleMe" href="#">JPortal, version @ViewContext.Controller.GetType().Assembly.GetName().Version</a></span>

Next, bind the click action using the class and disable the default href action on document ready:

$(document).ready(function(){
 $('.toggleMe').click(function(){
     $('#VersionHistoryList').toggle();
     $('#VersionHistoryList').focus();
     return false;
 });
});

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

The function assigned to [variable].onclick is not being executed, despite no errors being displayed in the console

I'm new to javascript and I'm looking for help with a simple task. I want to create a code that when clicking on an image, it will open in a modal. This feature is important for viewing full-size images on my portfolio. Although there are no erro ...

What is the best way to align product cards side by side instead of stacking them on separate lines?

I am currently working on a mock-up website for a school project. For this project, I am developing a products page where I intend to showcase the items available for sale. Although I managed to successfully copy a template from w3schools, my challenge lie ...

Rotate the horizontal scroll of an inner div within an outer div using CSS

I am looking to create an outer div with horizontal scroll and inner div with vertical scroll where the inner div moves along with the outer div. <body> <div id="wrapper"> <div id="outer">content outer <div id="inner"&g ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...

Learn the process of adding transformation to an SVG path element

I have an SVG image loaded in my HTML file and I am trying to rotate one of its path elements, but I'm having trouble figuring out how to do it. The code snippet provided below is not working as expected. Can anyone provide guidance on how to achieve ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

Is there a way to adjust the slide length in JQuery's slideUp function using pixels? It seems like

At the bottom of a page, I have a fixed position div element. There is another div below it, but it is hidden outside of the page margins. I am attempting to slide both divs upwards so that the bottom one becomes visible (moving out of the margin). However ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself ...

A guide on implementing CSS and Styling in a React component

Struggling to style my React.js file that was converted from a standard web page. I have the original CSS but unsure how to use React for proper styling. Any assistance is welcomed! var NavBar = React.createClass({ render: function() { return ( ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

The synchronization and network bandwidth optimization of Angular and Firebase's three-way binding system

Is it possible to synchronize the text box content across various clients using Angular and Firebase? I am curious to know if Firebase will update the database with each letter I type. How does this process impact network bandwidth? Can you explain how it ...

What is the best way to ensure an input field and a button are aligned perfectly within the same div tag and of equal height?

During a recent HTML-CSS project, I encountered an issue where I struggled to ensure that two elements within a div tag were the same height. The elements in question were an input field and a button with an icon. Here is a snippet of the relevant HTML cod ...

What is the process for sending tinyEditory's content using ajax?

I recently incorporated the StfalconTinymceBundle into a Symfony2 project and it is functioning perfectly. However, I am encountering a problem when trying to submit the editor's content through AJAX. The editor's content does not seem to be bind ...

What is the method for retrieving individual items from an array stored within a dictionary?

Suppose there is an array of strings saved in a dictionary, and I want to retrieve the first element from that array. What steps should I take to achieve this? Here is the code snippet I have already written... public IC2Engineering GetReportResultsTable ...

The authorization process for uploading data to Azure Data Lake Gen2

Currently, I am working on generating a Shared Access Signature (SAS) client-side within my Node.js application. The primary goal is to allow users to directly upload files to my Azure Data Lake Gen2 Blob Storage container without streaming them through th ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

Using jQuery's toggleClass method to implement CSS transformations

I have a question about this situation Each time the button is clicked, jQuery toggles the class: .transition { background-color: #CBA; transform: translateX(100px) scale(0.5) rotate(180deg); } Within the <div class="container2"> And upon ...