Is there a way to make my JavaScript code function within an ASP.NET CSHTML file?

I am working on a web project where I have an HTML input for uploading a picture to my FTP server. I want to use JavaScript to detect changes on my upload button. This is the code in my CSHTML file:

    @using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { 
    enctype = "multipart/form-data" }))
    {

    <input id="uploadFile" placeholder="No file..." disabled="disabled" />
    <div class="fileUpload btn btn-primary">
        <span>Browse</span>
        <input id="uploadBtn" type="file" class="upload" />
    </div>
    <input type="submit" title="OK" />
} 

Here is my JavaScript code:

<head>
<script type="text/javascript" language="javascript">
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
    </script>
</head>

However, when I run the code, I receive the following error message:

0x800a138f - JavaScript runtime error: Unable to get property 'onchange' of undefined or null reference

I have tested the HTML and JS in a fiddle and they work fine, so it seems that there may be some compatibility issues between Razor syntax and JavaScript. Any suggestions on how to resolve this?

Answer №1

Consider this suggestion:

1.

<head>
<script type="text/javascript" language="javascript">

$(document).ready(function(){
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
});
    </script>
</head>
  1. Based on @StephenMuecke's input : It is advised to move your script right before the closing </body> tag for better practice.

    <body> .............. .............

    <script type="text/javascript" language="javascript">
    
    $(document).ready(function(){
      $('#uploadBtn').on('change', function() {
       $("#uploadFile").val($(this).val());
     })
    });   </script>
    

    </body>

3.In case you are using a separate script file with extension .js, you can try this approach

     $(document).on('change','#uploadBtn' ,function() {
         $("#uploadFile").val($(this).val());
      });

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

Exploring the process of cycling through "Fetch" JSON data in React.js for a dynamic slider component after setting it to state

Still getting the hang of React, so please go easy on me! My main objective is to retrieve data from my personal JSON server and display it on a custom "Slider" component that I'm working on. Following a tutorial, I wanted to challenge myself by usi ...

Choose either null or Integer as the data type for the dbtype in the SQL output parameter

I have a store procedure that may return null or an integer value as the registrationID output. How can I set up the dbtype to be either null or int in my C# code? p.Add("@TotalRebate", bk.TotalRebate); p.Add("@PromotionId", bk.PromotionId); p.Add("@Re ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Why is the background image not loading properly on first hover with CSS?

Whenever we load a page with a large image set as the background for a div, there seems to be a delay in displaying the image when we hover over the div. Is there a solution to this issue? I would prefer not to use a sprite image because I need to make alt ...

Scrolling smoothly with React-Leaflet

In my React-Leaflet project, I am aiming to implement a seamless zoom effect. I am aware that vanilla Leaflet supports this feature, as mentioned in this post, utilizing smoothWheelZoom. However, considering the compatibility issues between vanilla Leafle ...

Including a 3DS card to a Stripe Client for recurring payments

I'm encountering an issue when trying to add payment cards with 3DS authentication for existing customers who already have an active monthly subscription. The objective is to allow our clients to change, remove, and add cards to the Stripe Customer ob ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

Encountering an abrupt conclusion of JSON input error during a Post request on an API while utilizing an access token in a

When attempting to post user details to an API using the access token obtained during sign up, I encountered the following error message: Unexpected end of JSON input. Here is my code: postNameToApi() { console.log("inside post ap ...

Guide on repeatedly clicking the Cookie to enjoy Cookie Clicker on https://orteil.dashnet.org/cookieclicker/ with the help of Selenium and Python

I've been attempting to create a selenium program for playing Cookie Clicker, but I'm encountering some issues. Here's the code I have so far: from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains P ...

Having difficulty assigning a value to the RadNumeric Text box during the OnBlur event

One of the requirements I have is that, when a user enters any number in a text box and tabs out, leading zeros should be added to the value in the text box. function AddPaddingToInvestmentNumber(sender, args) { var textBoxVar = "<%=txt1.ClientID ...

Struggling to update a document fetched through a Mongoose model and handled as a promise

Check out update #2 for more detailed information I am encountering difficulties while trying to make a simple update to a document that has been retrieved by querying a container through a Mongoose model. The query using find has two populations, but oth ...

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

Ways to extract the first name and email address from a JSON payload

{ "userID": 1, "userHandle": "username", "first_name": "firstname", "last_name": "lname", "middle_initial": null, "email_address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e203d250e29232f27 ...

Enhancing Javascript Dialog Box with a Touch of Animation

Collaborating with the incredibly talented Mark Eirich has been an amazing experience. We have been working on revamping a JavaScript dialog box together, and Mark has set up something on JSFiddle that will be incredibly beneficial. However, I am seeking a ...

Transforming MongoDB array into a string within the database

I am facing an issue with parsing arrays from Mongo/Express. The array from the body appears to be correct when I check the response in the node console. However, the problem arises when I attempt to save the body to the Mongo database using the insert.one ...

The initial click on a jQuery event is not registering as expected

My webpage includes a code snippet like this: $('#language_id').change(function () { var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id; $.ajax({ type: "GET", url: urli, dataType: &ap ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

Using JavaScript to display dynamic data pulled from Django models

I am currently in the process of designing my own personal blog template, but I have encountered a roadblock when it comes to creating a page that displays previews of all posts. This particular page consists of two columns, #content-column-left and #conte ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...