The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App

View

<form>
<div class="container">
    <div class="row">
        <div class="col-md-offset-2 col-md-4">
            <div class="form-group">
                <input type="text" class="form-control small" asp-for="UserName" />
            </div>
            <div class="form-group">
                <input type="text" class="form-control small" asp-for="Password" />
            </div>
            <div class="form-group">
                <a class="btn btn-sm btn-success pull-right" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin()">Log In</a>
                <input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" />
            </div>
        </div>
    </div>
</div>

TypeScript Code

   function ValidateLogin(e:Event) {
    var username = (document.getElementById('UserName') as HTMLInputElement).value;
    var password = (document.getElementById('UserName') as HTMLInputElement).value;
    if ((username.length > 0) && (password.length > 0)) {

    }
    else {
        alert('Fields required');
        e.preventDefault();
    }
}

If fields are empty than it should terminate the request , but it only display alert and e,preventDefault() is ineffective here .

I also tried return false , but nothing seems to work here . It should not go to action method after preventDefault or return false statement

Can somebody tell me what am i missing here in this very simple task ?

Update 1

If i change the code in below way , than it works

document.getElementById('btn').onclick = function (e) {
var username = (document.getElementById('UserName') as HTMLInputElement).value;
var password = (document.getElementById('UserName') as HTMLInputElement).value;
if ((username.length > 0) && (password.length > 0)) {

}
else {
    alert('Fields required');
    return false;
}

}

Still i dont know why it is not working when i wrap it in a method instead of calling directly with .onclick()

Answer №1

Attempting to use 'return false' did not produce the desired result, preventing the action method from executing after preventDefault or return false statements were invoked.

In reference to kemicofa's response, it is noted that your ValidateLogin function expects an Event parameter, but instead a this value was provided.

An examination of your code reveals:

<input type="submit" value="LogIn" asp-action="Validate" asp-controller="LogIn" onclick="ValidateLogin(this)" />

The usage of ValidateLogin(this) implies passing the input DOM element to the ValidateLogin() function as a parameter, which fails due to the absence of a preventDefault method for the Input element.

I am still uncertain why wrapping this in a method rather than calling directly with .onclick() does not yield the intended outcome.

To clarify, in this context, the this keyword references the specific DOM element to which the event handler is attached. However, this is not an instance of Event.

If you opt to bind the event handler using the on{eventtype}="script_code" HTML attribute, consider utilizing the event variable:

event can be treated as a predefined local variable within your script_code. For further information, refer to Registering on-event handlers.

Whether applying .onclick=function(event){/**/}; through JavaScript or invoking ValidateLogin(event) via an inline HTML attribute, both methods should perform as expected.

Answer №2

onclick="ValidateLogin(this)"

Your issue lies within the ValidateLogin method. You are passing the "this" context, but your method is expecting an event parameter.

A better approach would be to do the following:

<form onsubmit="ValidateLogin()">

Remove the onlclick attribute from your submit button.

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 data for my registration is not getting stored in the Firebase database as expected

I'm currently working on a registration app and it's my first time using firebase. My email address is successfully stored in the authentication section of firebase. However, when I try to connect my app to the database to store additional infor ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

The event listener function is not functioning properly on images generated by JavaScript

I'm currently working on placing multiple images on a grid in the center of the page and would like to include a function that triggers when each individual image is clicked. The images are dynamically created using JavaScript and inserted into the do ...

What is the reasoning behind AngularJS 2 HTTP Post only allowing string data as input?

Can someone explain to me why the HTTP Post method in AngularJS 2 (2.0.0-beta.13) only accepts string data as body, unlike in AngularJS 1 where it can accept a JavaScript object? AngularJS-1: $http.post(someUrl,someObject) AngularJS-2: http.post(someUr ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

The log indicates that there are two distinct IP addresses associated with the user

I find that this question may be better suited for another Stack Exchange board, and I am open to migrating it there if needed. In the development of a web application, we record certain event information to assist in diagnosing any potential issues. One ...

Is it possible to leverage both functions and variables within the ng-options expression in Angularjs?

I am faced with a situation where I have 2 select boxes. The first one is used to choose the user type (such as groups or individual), and the second one displays the options based on the selection made in the first box. I was wondering if it is possible t ...

What steps should I take to insert a divider in a dropdown menu?

I am attempting to enhance my dropdown menu by incorporating a separator using the following code: <li class='divider'></li> Below is my HTML code with the separator included: <ul class="dropdown-menu dropdown-menu-right" id="ul ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Eliminate placeholder text when the tab key is pressed

I'm currently facing an issue with a textarea that has a placeholder and the Tab key functionality in Internet Explorer. I've included placeholder.js to make it work, but when I repeatedly press the tab key and focus on the textarea, the placehol ...

What is the most efficient method for executing multiple variable=function() and determining when all tasks have been finished?

I am facing the issue of having multiple variables that need to be calculated before being saved as a JSON file. These calculations are done using a function, but when run asynchronously, they end up undefined. After reading about promises, it seems like t ...

Running various IT blocks within a Protractor loop to enhance web testing

After logging in to a web page, we need to use a for loop to perform multiple tests on the page. The ideal test scenario involves a table with buttons on each row that leads to another page where data needs to be validated. Currently, all expectations and ...

What is the purpose of employing this expression in the context of requestAnimationFrame?

Can you explain the purpose of using this specific "if" statement in relation to requestAnimationFrame? if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime ...

Using Ajax and jQuery to redirect a page with values in ASP.NET

I have two pages: Default.aspx and DetailView.aspx. My goal is to redirect from Default.aspx to DetailView.aspx using an AJAX call and pass a value as well. Although I have tried something, the function defined in the class is not being called. The functi ...

"Error encountered when attempting to upload directory due to file size

Utilizing the webkit directory to upload a folder on the server has been successful, however, an issue arises when there are more than 20 files in the folder. In this scenario, only the first 20 files get uploaded. The PHP code used for uploading the fold ...

How can I retrieve the values of jQuery select2 tag list in ASP.NET?

I am looking to retrieve the selected values from the jQuery Select2 plugin in my ASP.NET code behind. Below is a snippet of my code: Client Side: <select id="ddlcountry" runat="server" class="select" style="width: 100%;"> ...

Developing 2 potential results from textarea input using NODE.JS and HTML

Today, I encountered an issue while working on my bot website project that responds to textarea input. When I attempted to test it with two different commands, one of the commands stopped working unexpectedly. I'm puzzled by this and would greatly app ...

Mongoose sparks a confrontation following the preservation of a single document in the database

I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, whe ...

How can we make sure the selected tab opens in jQuery tabbed content?

I'm trying to make my tabbed content open on a specific tab by changing the URL. I remember seeing something like this before but can't seem to find it! Here's the fiddle I created: http://jsfiddle.net/sW966/ Currently, the default tab is ...

Setting a unique identifier for a newly created element in JavaScript and the DOM

Is there a way to assign an element ID to a newly created element using JavaScript DOM? The code I've written generates a table that is displayed when a button is clicked. I'm looking to give this table a unique ID so it can have a distinct sty ...