Having trouble with JavaScript function returning false?

I am trying to call a JavaScript function on an ASP.NET button client click event and want to prevent postback. The function is working, but it is not preventing the page from posting back. Here is my JavaScript code:

function User2Check()
    {
        var user2id=document.getElementById("txtP2UserName");
        var user2password=document.getElementById("txtP2Password");

        if(user2id.value=='' && user2password.value!='')
        {
            alert("User name is required");
            user2id = document.getElementById("txtP2UserName").focus();
            e.preventDefault();                
            return false;
        }
        if(user2id.value!='' && user2password.value=='')
        {
            alert("Password is required");
            user2id = document.getElementById("txtP2UserPassword").focus();
            e.preventDefault();                
            return false;

        }


    }

The way I am calling this function is:

<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check();" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />

Please provide guidance.

Answer №1

The parameter in your javascript function is not being passed from the button's OnClientClick event. It appears that despite e being null, the function continues to run because the focus() calls are made before any operations on e. This may be causing unexpected behavior in the function.

Answer №2

It is recommended to use && instead of &

if(user2id.value!='' && user2password.value=='')

AND : The Function requires an argument, but you are calling it without any argument

You can achieve this by:

function User2Check(e)
{
    var user2id=document .getElementById("txtP2UserName");
    var user2password=document .getElementById("txtP2Password");

    if(user2id.value=='')
    {
        alert("User name is required");
        user2id=document .getElementById("txtP2UserName").focus();
        e.preventDefault();                
        return false;
    }
    if(user2password.value=='')
    {
        alert("Password is required");
        user2id=document .getElementById("txtP2UserPassword").focus();
        e.preventDefault();                
        return false;
    }

    return true;
}

}

<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check(event);" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />

Answer №3

Try using the following code without including " e.preventDefault();" in it.

function User2Check()
{
var user2id=document .getElementById("txtP2UserName");
var user2password=document .getElementById("txtP2Password");

if(user2id.value=='')
{
    alert("User name is required");
    user2id=document .getElementById("txtP2UserName").focus();
    return false;
}
if(user2password.value=='')
{
    alert("Password is required");
    user2id=document .getElementById("txtP2UserPassword").focus();
    return false;
}
  return true;
}

Also, on the server side code make sure to include

<asp:Button runat="server" ID="btnSubmit" OnClientClick="return User2Check();" TabIndex="12" Text="Submit" onclick="btnSubmit_Click" />

Answer №4

There is a typo in the function name - it should be focus();

Once that error occurs, the program will halt execution.

Answer №5

If it seems like you aren't getting a true response, try adding an exclamation point before the function name. Here's an example:

!function(){
    // Your code goes here!
}

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

`html2canvas encountered an issue: Unable to locate a logger instance`

When I use html2canvas to render the same content repeatedly, I encounter an error about 5% of the time. It seems to be sporadic and I'm not sure why it occurs. What could be causing this unpredictable behavior? html2canvas.js:2396 Uncaught (in promi ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

What is the best way to access and interpret a JSON file within an Angular application?

I am facing difficulties while trying to load a JSON file from my local disk in order to populate a FabricJS canvas with the data. Currently, I am encountering issues retrieving the data from the file. Here is what I have attempted so far. app.html < ...

I encountered an error while attempting to lint my code because ESLint was not configured to ignore the

Trying to set up eslint in a Next.js project, here is the file structure: .eslintignore .eslintrc.js .next .prettierrc .stylelintrc.js components forms modals modules node_modules In my .eslintignore file, I have added node_modules/*. When running eslint ...

Discovering the length of an array using JavaScript

I have a question that may seem silly: How can we accurately determine the length of an array in JavaScript? Specifically, I want to find the total number of positions occupied in the array. Most of you may already be familiar with this simple scenario. ...

Guide on sharing a Vue project with other devices within a network

I'm a complete beginner when it comes to vue.js. After working on a few small projects, I want to make sure I understand how to share a vue project with others at this stage. Typically, I know that running 'npm run serve' in my project dir ...

Is the Three.JS camera update causing issues with the shader?

Attempting to replicate the Bubble shader from https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Bubble.html, but encountering issues due to outdated code. The example should refract whatever is behind it, like this: https://i.sstatic ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Tips for organizing AJAX code to show images and videos in HTML with a switch case approach

I have 2 tables, one for images and one for videos. Within my HTML code, I have three buttons: slide_image, video, and single_image. Using iframes, I am able to load images and videos on the same page. When I click on the slide_image button, it displays im ...

"How can I dynamically set the text for a radio button using Reactive Forms? Also, how do I capture the selected radio button value and the question title

If I use a reactive form-array, can I dynamically add 2 questions and 3 or 4 choices? Question 1: How do I set the radio button text dynamically using form-array? Question 2: Now, I'm attempting to retrieve only the selected choice ID corresponding ...

The issue with VueEditor in Nuxt.js is that it's throwing an error

When working on my Nuxt.js project, I integrated the vue2-editor package for writing articles with HTML. Everything functions properly when I enter text and submit it, however, upon reloading the page, I encounter an error stating "document is not defined" ...

Trouble with Directive - the watch function isn't functioning as expected

After spending countless hours and trying almost everything, I can't seem to get it to work... I have an Angular directive that calls another Angular directive. I need to handle events in the child directive. So my child directive looks like: ...

The JavaScript function is not returning the correct string when implemented in an HTML

I have written a function in a JavaScript file to return a string, and I am calling this function within a script tag inside an HTML file. function getExp() { var exp = "]]><!\\[CDATA\\["; return exp; } However, when I c ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

Guide on Adding Tawk.to Widget to Your Next.JS Website

I followed the instructions on their @tawk.to/tawk-messenger-react plugin documentation, but I am still facing issues. I created a component named /components/Chat.js import TawkMessengerReact from "@tawk.to/tawk-messenger-react"; export defaul ...

Is it possible to utilize a controller within a different controller?

As I work on developing an application, I am faced with the challenge of using controller functions within another controller function. Is it possible to achieve this or not? Use-case: My goal is to verify in the User collection (using mongoDB) if a user ...

Launch Internet Explorer and input variable values (such as ScriptEngineMinorVersion)

I am looking to create a script that can open a file and inject values into it. Here is a basic example: Set WshShell = WScript.CreateObject("WScript.Shell") Return = WshShell.Run("iexplore.exe google.com", 1) However, I also need to modify some variab ...

Sending JSON data two times to the ASP.NET MVC controller via POST request

function onTestComplete(content) { var url = '<%= Url.Action("JsonTest","Organization") %>'; $.post(url, null, function(data) { alert(data["name"]); alert(data["ee"]); }); } <% using (Ajax.BeginForm("JsonTe ...

Issue with Initiating Html5Qrcode Scanner Automatically Following Form Submission

I'm currently utilizing the Html5Qrcode scanner within a WordPress plugin to scan barcodes for products. My workflow involves: 1. Initiating the Html5Qrcode scanner and scanning a barcode. 2. Using the decoded barcode value to search for and display ...