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

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...

Steps for running the function saved in variable `x`, with the value `function(){alert('a')}` assigned to it

How can I achieve this using javascript? var x = 'function(){ ... }' x = x.toFunction(); x(); Previously, I used var x = '...'; eval(x), but I have learned that this method is inefficient and slow. To provide some context, my goal is ...

Creating a stylish gradient text color with Material-UI's <Typography /> component

Is there a way to apply a gradient font color to a <Typography /> component? I've attempted the following: const CustomColor = withStyles({ root: { fontColor: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)", }, })(T ...

Encountered a problem when incorporating delay functions into redux-saga testing using the Redux Saga Test Plan library

I am facing a challenge while trying to test my redux-saga functions using the Redux Saga Test Plan library. The issue arises due to delay functions present in my saga. All tests pass smoothly without any errors when I remove the line containing yield del ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

What is the best way to make tooltips track a specific data point they are connected to in D3?

I am working with a figure created using D3 that includes tooltips appearing near a data point when hovered over and can be pinned by clicking on the point. I have implemented the functionality to change the plotted values for the points by clicking on spe ...

The issue with Multiselect arises when the array is being set up initially

Using primeng Multiselect, I have implemented a logic to push data based on search value from the backend. To avoid the error of pushing undefined elements, initialization is required before pushing. However, when I initialize the dropdown's array var ...

What is the best way to retrieve the second to last element in a list

When using Protractor, you have convenient methods like .first() and .last() on the ElementArrayFinder: var elements = element.all(by.css(".myclass")); elements.last(); elements.first(); But what about retrieving the element that comes right before the ...

Blending ASP.NET Core 2.0 Razor with Angular 4 for a Dynamic Web Experience

I am currently running an application on ASP.NET Core 2.0 with the Razor Engine (.cshtml) and I am interested in integrating Angular 4 to improve data binding from AJAX calls, moving away from traditional jQuery methods. What are the necessary steps I need ...

Notifications for AngularJS tabs

I need help finding a method to incorporate "tab notification" using AngularJS, in order to show that there are important alerts that require attention. For example: (1) (3) TAB_ONE TAB_TWO TAB_THREE Could you provide any recom ...

Tips for retrieving the content of an input field using Angular

function HomeController($scope, navbarService) { var vm = this; $scope.showHeader = true; $scope.userNameNav =''; $scope.$on('toggleHeader', function(event, data) { $scope.showHeader = data; }); $s ...

At what point is the args variable required by Dojo?

There comes a point when passing the args variable to an anonymous function in Dojo becomes necessary, even though the function itself may not visibly need it. This can lead to confusion as there is no clear indication on the Dojo help page regarding whe ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Errors in Data Capture from AJAX Dropdown Selections

Recently, I've encountered an issue with one of my data fields while attempting to save it to a mySQL database. The problem seems to be related to the fact that the 'id' for the text value is saved instead of the actual text value itself, wh ...

Navigation Bar Dropdown Menu Not Responding to Clicks

I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some rea ...

Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array. Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on. I was trying to dynamically process my data within d3&apo ...

tips on assigning a unique ID to an item in a firebase database collection

My code is structured like this: const userCollectionRef = collection(db, 'users'); Then I add data using the following method : const addInfoToDataBase = async () => { checkLike(); await addDoc(userCollectionRef, { likePost: us ...

ScrollReveal.js won't function as intended

https://i.stack.imgur.com/SOQEk.png Looking to utilize the popular ScrollReveal.js created by Julian Lloyd (ScrollReveal) Despite following instructions from various sources, the script is not producing the intended effect. Steps taken to make it work: ...

scrollable material ui chips list with navigation arrows

I'm attempting to create a unique scrollable chips array using Material UI version 4 (not version 5). Previous examples demonstrate similar functionality: View Demo Code I would like to update the scrolling bar of this component to include l ...