modify the label text when the @Html.TextboxFor in MVC3 triggers the onchange event

Currently, I am working with MVC3 Razor and trying to modify the text of a label based on the onchange event of @Html.TextboxFor.

Below is the code snippet that illustrates what I am attempting to achieve:

In View:

@Html.TextBoxFor(x => x.ItnScanCaseCode, new { @onchange = "event();" })

JavaScript Function:

function event() {
    document.getElementById('lblSelectedProductName').value ="sam";
}

Despite my efforts, it appears that this implementation is not functioning as intended.

Answer №1

Here is a useful jQuery syntax that works perfectly:

@Html.TextBoxFor(x => x.ItnScanCaseCode, new { @id="txtid", @onchange = "onchangeevent();" })

function onchangeevent(){
        $('#txtid').val('sam');
    }

Answer №2

To achieve this task, I rely on JavaScript, although I prefer using jQuery for its ease of use. My approach involves keeping my HTML and JavaScript code separate, listening for the on change event only after all controls have been loaded into the DOM.

An example of HTML markup for a text box with a custom label element:

<input id="ItnScanCaseCode" name="ItnScanCaseCode" type="text" value="" />
<label id="lblSelectedProductName">Test Label Text</label>

Here's the jQuery script to assign an on change event listener:

$(document).ready(function () {
     $('#ItnScanCaseCode').change(function () {
          $('#lblSelectedProductName').text('sam');
     });
});

If you wish to encapsulate the label text changing functionality in a separate function method, you can do so like this, but the previous approach works well enough for me:

$(document).ready(function () {
     function yourEventMethod() {
          $('#lblSelectedProductName').text('sam');
     };

     $('#ItnScanCaseCode').change(function () {
          yourEventMethod();
     });
});

I trust that this explanation is helpful.

Answer №3

If you're encountering an issue with the event name, consider changing it to something else. This should resolve the problem.

@Html.TextBoxFor(x => x.ItnScanCaseCode, new { @onchange = "onchangeevent();" })

function onchangeevent(){
        document.getElementById('lblSelectedProductName').value ="sam";
    }

Best Regards

Answer №4

Give this a shot!

  @Html.TextBoxFor(model => model.Picture, new { type = "file",
                       @onchange = "displayImage(this);" })

This is where my custom JavaScript resides

<script type="text/javascript">

   function displayImage(input) {
      if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
         $('#preview_img').attr('src', e.target.result);
      }
      reader.readAsDataURL(input.files[0]);
   }
}
</script>

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 date field does not show a dropdown menu in the popup window of SugarCRM

Hey there! I've encountered an issue with displaying a datetime field in a popup. When I add a datetime field to the Advanced Search of ProspectLists, it appears as shown below and functions correctly: Within the custom modules ProspectLists searchde ...

Ways to make the submenu display underneath the main menu

Click here to view the menu It is important to note that you may need to expand the Result Box in order to see the full menu. The issue I am currently facing involves fixing a submenu that appears when hovering over the Men and Women <li> elements. ...

Why is my component not utilizing the implementation in this Jest mock?

I'm currently attempting to run tests on a React component using Jest. Within the component, there is a required module that acts as a factory function returning an object of functions. //tracker.js export default () => { track: click => doso ...

Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37 The error message is as follows: Type '{}&a ...

Exploring the functionality of `GET` and `POST` parameters within Static Assets in ExpressJS

When utilizing PHP to generate pages that rely on the request parameters of GET and POST, we can achieve something similar by: <p>Hello, <?php echo $_GET["name"]; ?>!</p> For instance, if we access the file like: /?name=Mike, the output ...

What could be causing the side menu to not collapse?

Recently, I developed a side menu using HTML, CSS, Bootstrap, and JavaScript. The menu appears to be functioning correctly: clicking on "Student Management" reveals the corresponding submenu, while clicking on "Invoicing Management" hides the former and di ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

JavaScript can be used to enable or disable a text box within a GridView when a checkbox is changed

I have a GridView on a webpage containing a Textbox and a CheckBox. I want the Textbox to be enabled when the CheckBox is checked, and disabled when it is unchecked using pure javascript. Can anyone help me solve this issue? Thank you in advance. <asp ...

The Middleware does not catch Promise rejections that occur with await

I'm currently utilizing Nodejs in my project. One issue I am facing is with a promise that is requested after a delay. It seems like my Middleware is unable to catch the error, however, uncaughtException is able to handle it. router.all('/incas ...

What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps p ...

Accessing nested arrays and objects within JSON using Node.js

I'm in the process of developing an application that retrieves a JSON response from an API call using SONARQUBE. With node js, how can I extract the value of duplicated_lines from the following JSON object? I attempted the code below but it always r ...

Accessing Cognito using ReactJS and fetching data with specific parameters

I'm currently attempting to retrieve the email of the user who is logged in and use it within my fetch() call. I have successfully obtained the email using getfirstapi() and used it in my form, but I am encountering issues when trying to pass it into ...

Looking to upgrade nested dependencies within an npm package?

I am currently facing an issue with the 'request' npm package, which is deprecated and installed as a dependency by another npm package. I have been trying to update the dependencies of the request package but have not been successful in finding ...

Attempting to incorporate icons into a Material UI table design

Hello, I've incorporated a Material UI table into one of my projects with a design concept similar to this - https://i.stack.imgur.com/i6Fsj.png I'm aiming to include icons within the tables. Here's the code I've worked on so far - ...

Tips for loading the .run file prior to the controller's execution

In my Cordova app, I am working with a pre-populated database and trying to display the result of a database search in a <select> element without using ng-click in my HTML file. Currently, the only solution I have found is to use ng-click, but I want ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their favorite list. View: <div class="col col-33"> <i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-ic ...

Guide to making a custom scoreboard in JavaScript for my gaming application

Being a beginner in coding, I've been working on a Battleship-like game. I've managed to do most of it, but the scoreboard isn't functioning. I'd appreciate any guidance on how to fix it or what changes are needed for it to work properl ...

The function toDataURL() in Canvas is storing images in low resolution

I created a unique polygonal background generator using HTML5 canvas which can be found at the following link: http://codepen.io/rfalor/pen/LhinJ Here is the important part of the code: var canvas = document.getElementById("canvas"); var ctx = c ...

Can you assist me in determining the source of data for the API in ASP.NET MVC?

As a novice, I find myself working on an MVC project that I have yet to fully grasp. Connecting in the Login Screen has left me puzzled as to where the API retrieves its data from. It seems not to be using Entity Framework and there is no json file contain ...