Razor coding and the power of JavaScript

I have developed an ASP.NET MVC application and am facing an issue with translating the functionality I have implemented in Razor to JavaScript. In the example below, I have successfully created three buttons in Razor with a working script. However, when I tried to replicate the same functionality using a helper in JavaScript, the script within the script did not work properly. Additionally, there seems to be an issue with the recognition of the bootstrap layout containers. How can I resolve this issue and correctly implement the functionality in JavaScript?

Razor (working well)

panelbar.Add().Text("Third Person")

          .Content(@<div style="padding: 10px;">
              <div id="cont5_container" class="container">

                          <span class="label label-primary">Age</span>
                          <br />
                          <br />
                          <div class="btn-group" id=ageID2>
                      <button type="button" style="width:120px" class="btnMyAge5 btn-default" id="3">Under 10</button>
                      <button type="button" style="width:120px" class="btnMyAge5 btn-default" id="1">Under 50</button>
                      <button type="button" style="width:120px" class="btnMyAge5 btn-default" id="2">Over 50</button>

                      @Html.TextBoxFor(m => m.ageID, new { @class = "input k-textbox", id = "MyAge5", Value = "", style = "width: 50px;" })
                  </div>

                  <script>
                      $(".btn-group > .btnMyAge5").click(function () {
                          $(this).addClass("active").siblings().removeClass("active");
                          document.getElementById('MyAge5').value = $(this).attr("id");
                      })
                  </script>
               </div>

           </div>);

JavaScript (Can't be correct)

<script type="text/javascript">

function OnClickAdd() {
    $("#panelbar").kendoPanelBar();
    var panelBar = $("#panelbar").data("kendoPanelBar");

    panelBar.append(
        {
            text: "New Person",
            encoded: true,
            content: [

                         '<div id="cont6_container" class="container">',
                                '<span class="label label-primary">Age</span>',
                                '<br /><br />',
                                  '<div class="btn-group" id=ageID>',
                                     '<button type="button" style="width:120px" class="btnMyAge3 btn-default" id="3">Under 10</button><button type="button" style="width:120px" class="btnMyAge3 btn-default" id="1">Under 50</button><button type="button" style="width:120px" class="btnMyAge3 btn-default" id="2">Over 50</button>',
                                     '@Html.TextBoxFor(m => m.ageID, new { @class = "input k-textbox", id = "MyAge3", Value = "", style = "width: 50px;" })',
                                 '</div>',
                           '</div>'
                    ]
           }
                  )
                        }

<script>
$(".btn-group > .btnMyAge3").click(function () {
    $(this).addClass("active").siblings().removeClass("active");
    document.getElementById('MyAge3').value = $(this).attr("id");
})

Answer №1

Upon further investigation, it appears that the issue arises when the click handler in the second script tag is triggered before the content from the first script tag is fully integrated into the DOM. To resolve this, consider implementing the click handler within the same function responsible for adding the button to the HTML structure.

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

"Revolutionary AJAX-enabled PHP social commenting system with multi-form support

Why is it that when I submit forms using these ajax functions in PHP, they only send to the first form on the page? I have multiple forms under each article and I want them to be submitted separately. What am I doing wrong? ...

Issue encountered while connecting ipcRenderer with ipcMain in an electron application

I recently set up Angular CLI in Electron, and I have a link that triggers a function which communicates between ipcRenderer and ipcMain: Here is the HTML code: <a (click)="check()"> click </a> This is the component code: constructor(privat ...

Prompting initiation parameters for Silverlight urging installation of Silverlight on Mozilla and Chrome browsers

Encountering an issue with a Silverlight control's behavior on an ASP.NET page. The control functions correctly in IE, but in Mozilla, a message prompting to 'install Microsoft Silverlight' appears. After several trial and error attempts, i ...

Guide on utilizing loader.load() function to load a compressed file in three.js - Instructions on loading filename.json.gz

I've already compressed a file into a .gz file and stored it in S3. You can find it here: However, when I attempt to load it in Three.js using loader.load("https://oic-accounts.s3.ap-south-1.amazonaws.com/3d-try-json-files/gzip/3.json.gz", ...

Tips for retrieving the selected option from a dropdown menu

I have a dropdown menu with checkboxes that can be selected using SumoSelect. Here is the markup for the dropdown menu: <select multiple="multiple" name="somename" id="uq" class="select"> <option value="volvo">Volvo</option> <o ...

Tips for parsing JSON data in C# methods

Last night was dedicated to solving this puzzle. After some trial and error, I've cracked generating directions on Google Maps using client-side JavaScript between two user-selected points. Now, the challenge is storing these directions in my C#.NET ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

The functionality of selecting all items in v-select does not result in saving all of them

I'm currently working on integrating a select all button into the v-select component of Vuetify. The issue I am facing is that even though I can use the button to select all options, when I attempt to save, not all items are saved. However, if I manua ...

Tips on resolving viewstate MAC authentication failure in ASP.NET

The issue occurs on both the server and localhost. Error: The validation of viewstate MAC failed. If this application is hosted on a Web Farm or cluster, make sure that the configuration specifies the same validationKey and validation algorithm. Auto ...

Leveraging useEffect (or a comparable method) within a class component to create a loading screen

As a React newbie, I recently created a loading screen using useEffect in a functional component. Now, I'm trying to achieve the same using class components, but I'm facing some challenges. Here is the functional component that works perfectly: c ...

Struggling to make the transition from JavaScript to TypeScript in Ionic 2

I recently updated the file extensions for my application files, including app/app.js. Error: Cannot find module 'app/app.js' from 'app_folder' The error message doesn't specify which file I need to locate to resolve the issue. ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...

Having difficulties transmitting numerical values through res.send() in express with node

Currently, I'm faced with a challenge in my express application on node.js as I attempt to retrieve the "imdb rating." movies.json [{ "id": "3962210", "order": [4.361276149749756, 1988], "fields": { "year": 2015, "title": "David and Goliath" ...

Ways to horizontally align 2 rows in React

I am in the process of developing a react app and I have encountered an issue with aligning the field names horizontally with their corresponding field values in multiple columns. Despite my efforts, the alignment still appears to be a bit off. Below is th ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Developing a calendar with limited availability for selecting future dates and restricting the ability to choose past dates

I am currently working on creating a calendar in Vue.js that allows users to select dates only from the current day up to the next 30 days. Dates prior to the current date are disabled, as well as dates beyond the initial 30-day period. While I have exper ...

Flask causing AJAX Request to encounter a CORS Policy issue

Currently, I am utilizing Flask to construct a basic backoffice system. In an attempt to execute some requests on the client-side using AJAX, I keep encountering a persistent error: Access to XMLHttpRequest at '...' from origin 'http://lo ...

Changing a value within a JSON object

I need to update the "Last" Price for MarketName USDT-BTC. How can I change the value from 16750.00000001 to 17000.00000001 and then transmit it through my API? { "success":true, "message":"", "result":[{ "MarketName":"USDT-BTC", "High":16 ...

Purge the cache at a designated time within ASP.NET 2.0

I have a system that runs a process at midnight to set parameters for a flash object. This process only needs to run once a day, so I am caching the results for efficiency. The issue I am encountering is that if the data is still cached after midnight, it ...