JavaScript function for validating CGPA or GPA fields

I am encountering issues with JavaScript validation in ASP.NET. The validation seems simple, but for some reason, it is not functioning properly.

Below is the code that I have tried:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="gpavalidation._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        function gpa()
        {
            var reg = /[0-9][.][0-9]/;
            if(!reg.test(document.getElementById("cgpa").value))
            {
                return false;
            }
            else
            {
                return true;
                alert("correct value");

            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        GPA:<input type="text" name="cgpa" id="cgpa" maxlength="3" onclick="return gpa();" />
        <input type="submit" name="name" value="submit " />

    </div>
    </form>
</body>
</html>

However, the code is not producing the desired outcome...

What I am looking to achieve: I want the user to only be able to input numeric data in the GPA field, such as 3.4, 4.0, or 2.1. How can I achieve this result?

Any assistance on this matter would be greatly appreciated.

Answer №1

Give this code a try for your solution. It is just as simple as your current code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
       return false;
    return true;
}
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     GPA:<input type="text" name="cgpa" id="cgpa" maxlength=3 onkeypress='return isNumberKey(event)' />
    </div>
    </form>
</body>
</html>

For further assistance, you can also check out www.technogupshup.com/p/gtu-calculate-your-percentage-from.html. This link provides guidance on clearing the input validation and obtaining output results for converting cgpa to percentage.

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

recording JSON requests in expressJS

Update: Apologies for the confusion, I have realized that I needed to move the app.use(express.logger('dev')); higher up in the program. This adjustment has resulted in logging every GET and POST request successfully. Express server now listeni ...

There is no value inputted into the file

I'm facing a small issue while trying to retrieve the value from my input of type="file". Here is the code snippet: <tr ng-repeat="imagenDatos in tableImagenesPunto | filter: busquedaDatosPunto " > <td>PNG</td> <td>{{imag ...

The background of the ACTK Modal Popup vanishes after multiple instances of scrolling up and down

The issue I'm facing is with the AJAX Control ToolKit Modal Popup's background (the blind curtain) disappearing after scrolling up and down several times. I have attempted to resolve this by applying various CSS styles, but unfortunately, none of ...

JQuery selecting and highlighting a row within a dynamically loaded table via ajax

On a webpage, there are two tables being displayed. The first table loads along with the entire page, while the second table is loaded later on using ajax. Each row in both tables contains links. Upon clicking a link, the corresponding row in the table ...

Navigate within the div by scrolling in increments of 100%

I am facing an issue with a div that contains multiple children set to 100% height. My goal is to scroll exactly the height of one child (which is also 100%) on each scroll. However, I am struggling to prevent scrolling multiple steps at a time. I have tri ...

Changing the size on click using Jquery

I'm attempting to make a button shrink another element using jQuery. Here's what I have so far: $( "#img1" ).click(function() { $("#img2").css("-moz-transform:scale", "0.7, 0.7"); }); However, this solution doesn't seem to be functio ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Saving a byte array as a downloadable file in ASP.NET MVC

Currently, I am working on downloading a docx file from a byte array. The process involves allowing users to upload multiple files, creating new model objects to store file information, editing the data, and then returning the new file to the user. I am us ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...

Utilizing data in mongoose: A beginner's guide

I have two database models: User and Conversations. The User model has the following schema: const userSchema = mongoose.Schema({ username: String, logo: String, ..... }) and the Conversation schema is as follows: const conversationSchema = mongo ...

The Core 2.2 fails to compare correctly with the function name() when the comparison is valid

Currently utilizing Razor pages for a registration form. Employing model binding to link the form to page model properties. Implemented the Compare(nameof()) data annotation to verify password field matching. Despite the two password fields matching, the c ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

The PasswordResetView in Django using Vue.js encounters a 403 Forbidden error when attempting to post with Axios due to an

I'm currently working on building a unique Email Restore page in the frontend using Vue.js. My goal is to send email input data via Axios to /api/v1/accounts/password_reset/, essentially utilizing the original ResetPasswordView as an endpoint instead ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

Restricting the frequency at which a specific key value is allowed to appear in JSON documents

Within my JSON file, there is an array structured like this: { "commands": [ { "user": "Rusty", "user_id": "83738373", "command_name": "TestCommand", "command_reply": "TestReply" } ] } I have a requirement to restrict the num ...

Eliminate any unauthorized characters from the email address

My goal is to assist users in avoiding entering invalid characters in an email input field (prior to server-side validation and cleanup). Please note: I am not validating emails on the frontend, only cleaning them up. // Coffeescript $(Element).find(&apo ...

Is there a simple way to delete an element from a multidimensional array object in React JS?

In my current project using React Js, I'm facing an issue with removing an item that corresponds to the "product_option_value_id". The task at hand is to remove an item from the product_option_value (a child array object) if the given itemId matches t ...

Issue with ThreeJs raycaster not returning correct event.clientY value when header bar is visible

Here's the issue: I'm trying to place a sphere on a 3D model when I click on it using ThreeJs raycaster. It works fine when the canvas covers the entire page, but if I add a header bar to the page, the positioning is off. Here are some visual ex ...

What is the best way to transform the HTML retrieved from an AJAX GET request into an object using JQuery?

$.ajax({ method:"get", url:"/wall", data:"ajax=1", beforeSend:function(){}, success:function(html){ $("#grid_mason").append(html); //Inserting additional co ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...