Enhancing User Experience with Real-Time Control Updates using ASP.Net and Bootstrap

I am struggling to figure out how to update bootstrap controls with ASP.Net.

Here is the code I am working with:

@{
    Layout = null;
}
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title Mark Hub</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

    <script>
        var url = "http://localhost:51520/api/teacher/"

        function getTerms(course) {}
        $select = $('#termSelect');
        
        $.ajax({
            url: url + "global/currentterms/" + course ,
            dataType:'JSON',
            success:function(data){
                $select.html('');
                
                $.each(data.person, function(key, val){
                    $select.append('<option id="' + val.id + '">' + val.name + '</option>');
                })
            },
            error:function(){
                $select.html('<option id="-1">none available</option>');
            }
        });
    </script>
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Mark Hub", "Index", "Teacher", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Teacher", "Index", "Teacher")</li>
                    <li>@Html.ActionLink("Admin", "Index", "Admin")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="section">
        <div class="container">
            <div class="row">
                <div class="col-md-1 text-left">
                    <select class="form-control" id="courseSelect" onclick="getTerms()">
                        <option>DEC 10</option>
                    </select>
                </div>
                <div class="col-md-1 text-left">
                    <select class="form-control" id="termSelect">
                    </select>
                </div>
            </div>
        </div>
    </div>
    <div class="section">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <hr />
                    <footer>
                        <p>&copy; @DateTime.Now.Year</p>
                    </footer>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

I want to pass the selected value from courseSelect to the Javascript function getTerms, retrieve JSON data using a web api call, and dynamically populate the termSelect control.

However, changing a selection in courseSelect combobox does not update termSelect combobox.

What changes should I make to my code?

UPDATED WITH REVISED CODE BASED ON ANSWER SUGGESTIONS

<script>
    var url = "http://localhost:51520/api/teacher/"

    $(function(){
        $('#courseSelect').on('change',function(){
            var course =  $('#courseSelect').val();
            
            $.ajax({
                url: url + "global/currentterms/" + course,
                dataType:'JSON',
                success:function(data){
                    $select.html('');
                    
                    $.each(data.termID, function(key, val){
                        $select.append('<option id="' + val.id + '">' + val.name + '</option>');
                    })
                },
                error:function(){
                    $select.html('<option id="-1">none available</option>');
                }
            })
        })});
</script>

Despite updating the code as recommended, the functionality still doesn't work, and the breakpoint confirms that the function is not triggered upon selecting an option from courseSelect.

Answer №1

Instead of calling the function getTerms() on click of the select tag, it is recommended to use the on change event. While using click may work, it can also be triggered by clicking the text box, resulting in unnecessary API calls. Additionally, avoid using inline event binders as they are deprecated and will soon stop working in the future. It's best to bind events using on in jQuery. Modify your code as shown below.

Remove the onClick attribute from your HTML

<select class="form-control" id="courseSelect">
    <option>DEC 10</option>
</select>

Then, utilize this jQuery code:

$(function(){
   $('#courseSelect').on('change',function(){
          // This replaces your getTerms function
          var course =  $(this).val(); 
          // Include the rest of your logic here 
   });
});

Answer №2

the function in your javascript is named getTerms(course), but you are calling it in your click method as getTerms()

therefore, you need to make the following changes to your javascript:

function getTerms() {}
        //get a reference to the select element
        $select = $('#termSelect');
        $course= $('#courseSelect').val(); // this is how you get the value of course
        //your next code

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

Identifying a shift in data model within a component

It seems like there's a piece I might be overlooking, but here's my current situation - I have data that is being linked to the ngModel input of a component, like so: Typescript: SomeData = { SomeValue: 'bar' } Snippet from the vie ...

Is the Vis.js network function ready to go?

Utilizing the Vis.js network library to display graphs and am curious if there is a dedicated finishedLoading event available for this object? Any suggestions or insights are appreciated! ...

Ways to refresh my $scope once new data is inserted into the SQL database

As I implement the angularjs/SQL technique to fetch data from a database, the code snippet below demonstrates how it is done: $http.get("retrieveData.php").then(function(response){ $scope.tasks = response.data.tasks; }) In addition, there is a functi ...

Obtain the image URL using Selenium and Chrome WebDriver

Currently, I am utilizing selenium webdriver in C# to attempt to retrieve the src of an image by using the GetProperty method in order to confirm that the correct image is being displayed. var productImg = product.FindElement(By.TagName("img")); var produ ...

Not enough resources error in ajax code for live update clock functionality

Recently, I developed a real-time clock that updates every second. Surprisingly, when I tested it on my local environment, everything worked perfectly without any errors. However, the situation drastically changed when I decided to upload it to my web host ...

How to use jQuery to hide radio buttons that are not checked when clicking a submit

Looking to dynamically hide all unchecked radio buttons and their labels until a submit button is clicked, displaying only the checked radio button. <form method="post"> <input type="radio" name="radiobtn"> <label for="first">Fir ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Uninstalling NPM License Checker version

Utilizing the npm license checker tool found at https://www.npmjs.com/package/license-checker The configuration in license-format.json for the customPath is as follows: { "name": "", "version": false, "description&quo ...

Displaying iframes in AngularJS using a service

I am currently developing an Angular app and encountering some difficulties with rendering a Soundcloud embed iframe in my HTML. The issue arises when I try to display the tracks stored in the array generated by my getTracks function. Despite successfully ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

Tips for removing "<li>" elements using JavaScript

My issue remains unresolved... I created a tree structure in MVC and added JavaScript code for expanding and collapsing the tree. However, after applying the code, my tree is not being displayed correctly. enter image description here In the image, you c ...

Unable to load the threejs module

I am still learning about threejs and have mostly worked on projects using a dev server (vite) locally. This setup limited me to accessing my projects only from the browser on my computer. Here is how I typically include my files in these projects: <bod ...

Issue with arrow functions in Reactjs Material-UI - Unexpected token error

I am currently trying to integrate components from material-ui into a project based on react-rocket-boilerplate. An error message is appearing: [23:55:11] gulp-notify: [Compile Error] C:/react-rocket-boilerplate/app/js/components/Sidebar.js: Unexpected ...

Connecting nodes to edges based on their unique ids in the d3.js graph library

I am encountering an issue with this code while trying to integrate it with a new JSON object called 'new_json'. Specifically, I need the links in this code to be created based on the nodes' IDs. Can anyone provide assistance with this? va ...

Implementing Promises in AngularJS Controller: A Comprehensive Guide

I'm currently working on implementing a basic function using promises in one of my controllers to make sure it works correctly before adding more complex functionality. I keep running into a "TypeError: undefined is not a function" error when trying t ...

React's useState function causes the entire application to crash

Currently, I am working on setting up a basic menu using ASP.net core 2.1, Typescript 3.2.1, material-ui 3.8.3, and React 16.7.0. However, upon running the application, it crashes at the line containing useState showing the error message as TypeError: reac ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Using VueJS for reactive binding效果

I am attempting to assign a class using the following syntax: :class="{active: favs.medium_title.fontWeight === 'bold'}" However, the fontWeight attribute is not yet defined when the component loads. This is an excerpt from my object: favs: { ...

Keep deciphering in a loop until the URI string matches

I have a task to decode a string URI until there are no more changes. The string URI I am working with typically has around 53,000 characters, so the comparison needs to be fast. For demonstration purposes, I have used a shortened version of the string. B ...