Which is better for generating automatic value - Javascript or Controller?

I am currently exploring the most effective way to update a database value based on the input from a textbox. The database contains two columns: "Amount Added" and "Money". The value in the "Money" column depends on the "Amount Added" value.

My goal is to automatically update the textbox for "Money" once the "Amount Added" value has been changed, or have the controller calculate and input the value upon clicking submit.

I attempted to achieve this using JavaScript, although it is not my expertise. I found a code snippet in another post here:

$(document).ready(function Update() {
    var one = document.getElementById('AmountAdded'),
        two = document.getElementById('Money');

    two.value = parseInt(one.value) * 2 / 100;
})

Unfortunately, this approach did not work as expected. Should I continue with this method and refine it, or consider implementing it through the controller?

If relevant, I am utilizing Entity Framework for this project.

UPDATE: After realizing that the JavaScript was located within the body due to being in the view, I moved it to the layout page. Additionally, following Dhaval's advice, I corrected "GetElementById" to "getElementById".

Initially, the first reload displayed the "Money" value as NaN. To address this, I set the default value to 0. However, changing it subsequently does not reflect the updated value in Html.EditorFor.

Any suggestions or insights would be greatly appreciated.

Answer №1

$(document).ready(
    function(){
        UpdateValues();

        $('#AmountAdded, #Money')
            .change(function(){
                UpdateValues();
         });
    }
);

function UpdateValues() {
    var value1 = $('#AmountAdded'),
    value2 = $('#Money');

    value2.val(parseInt(value1.val()) * 2 / 100);
}

Answer №2

It appears that you are utilizing jQuery in your code. You may want to experiment with the following snippets:

$(document).ready(function(){
    $('#AmountAdded').on('change',function(){
        var calculation = $('#AmountAdded').val() * 2 / 100;
        $('#Money').val(calculation);
    })
})

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

There seems to be this strange and unexpected sharing of Animated.View and useRef between different child components

Currently, I am displaying a list of items in the following manner: {formattedJournal[meal].map((food, idx, arr) => { const isLast = idx === arr.length - 1; return ( <View key={idx}> ...

How to easily click on an empty space using Protractor

I am currently using Protractor to run tests on an Angular JS project. On one particular page, I need to trigger the auto save feature by clicking on any blank area after filling in all the required fields. However, I've been unable to figure out how ...

React Native - encountering undefined setState when passing data

I'm attempting to transfer data or items from one screen to another upon tapping the send button. However, the this.setState function in my "_onPress" method doesn't seem to be working correctly. When I tap the send button, the alert displays "un ...

Using TypeScript, you can access the constructor of a derived type by calling it with the

In my TypeScript project, I am attempting to generate or duplicate a child object using a method within the base class. Here is my simplified code setup: abstract class BaseClass<TCompositionProps> { protected props: TCompositionProps; prot ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

ASP.NET, utilizing Windows Authentication and the manipulation of querystrings

Situation: A website in ASP.NET C# is hosted on a Windows Server 2012 with SQL Server 2014. User authentication is done through Windows Authentication, configured in the web.config as follows: <authentication mode="Windows" /> <authorization> ...

What is the reason for JSHint alerting me about utilizing 'this' in a callback function?

While working in my IDE (Cloud 9), I frequently receive warnings from JSHint alerting me to errors in my code. It is important to me to address these issues promptly, however, there is one warning that has stumped me: $("#component-manager tr:not(.edit-co ...

Tips for hiding navigation items on mobile screens

I've been learning how to create a hamburger menu for mobile devices. Within a navigation structure, I have three components: Logo, nav-items, and hamburger menu. Utilizing flexbox, I arranged them side by side and initially hid the hamburger menu on ...

Selecting data in TSQL where two columns are equal to each other

I am working on creating a search function that identifies items in the same table based on their correlation. For example, if I enter the value a123 for the BoxNo column, then all values in the Goeswith column that are also a123 should be selected. The c ...

Renaming ngModel in an AngularJS directive's "require" attribute can be achieved by specifying a different alias

I need help with a basic AngularJS directive: <my-directive ng-model="name"></my-directive> I want to change the "ng-model" attribute to "model", but I'm unsure how to pass it to the "require" option in the directive. Here is the full co ...

Expanding unordered list with dual columns upon hovering

Could you possibly assist me with creating a unique navigation effect for my new website? I am aiming to achieve an expandable two-column menu on hover of a parent list item that contains a sub-list. So far, I have made some progress in implementing this ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Is there a way to integrate @Aspect with @Controller in Spring 3?

Currently, I am in the process of setting up a Spring 3 Web MVC project, utilizing the @Controller annotation-based approach. package my.package @Controller @RequestMapping("/admin/*") public class AdminMultiActionController { @RequestMapping(value = "a ...

End the sessions of all users sharing the identical JWT token

Currently, I am utilizing React and Nodejs while incorporating JWT for user authentication. An issue has arisen where multiple users are simultaneously logged in with the same email address such as "[email protected]". Our objective now is ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Employing TypeScript decorators to enforce a required parameter in functions

Working on a typescript project, I encountered over 2000 events(methods) that are triggered during user operations. To ensure performance metrics for all events related to the completion of an operation, I decided to make 'executionTime' a mandat ...

Using jQuery's .post() method to automatically scroll to the top of

Is there a way to prevent the automatic scrolling to the top of the page when executing the buy function? Here is the code snippet involved: <a href="#" onClick="buy(id)">Buy</a> The buy function utilizes the $.post() function for processing t ...

Using a JavaScript variable in a script source is a common practice to dynamically reference

I have a scenario where an ajax call is made to retrieve json data, and I need to extract a value from the json to add into a script src tag. $.ajax({ url: "some url", success: function(data,response){ console.log("inside sucess"); ...

Functionality of JavaScript limited within a form

Here is some HTML code I am working with: <div class = "login"> <form> <input type="text" id="username" name="username" placeholder="Username" style="text-align:center"> <br> <br> <input type="pa ...