Avoiding form submission in Internet Explorer 8 when clicking on a Dojo button

Here is the code snippet from my asp.net page:

<button dojotype="dijit.form.Button">
    <asp:Label ID="lblClear" runat="server" meta:resourcekey="lblClearResource1" />
        <script type="dojo/method" event="onClick" args="evt">
            return ClearCheckBoxes('<%=clientIds.ClientID%>');
        </script>
</button>

The function ClearCheckBoxes used in the code is defined as follows:

function ClearCheckBoxes(obj1) {
    var chks = document.getElementsByTagName("input");
    for (i = 0; i < chks.length; i++) {
        if (chks[i].type == "checkbox") {
            if (chks[i].checked == true) chks[i].checked = false;
        }
    }
    document.getElementById(obj1).value = "";
    document.getElementById('<%=clientsIds.ClientID %>').value = "";

    return false;
}

Although this code runs smoothly on most browsers, it triggers a postback in IE8. Is there any technique to prevent this unwanted postback specifically in IE8? I have tried using return false; but with no success in stopping the postback.

Answer №1

By default, a button's type is set to submit, which means it will submit any surrounding form when clicked. To prevent this behavior and use the button solely for its onclick function, you can specify type="button" within the <button> tag.

For example: (try removing type="button" to observe the impact in IE8)

<form>
    <button type="button" data-dojo-type="dijit/form/Button">Button
        <script type="dojo/method" event="onClick" args="evt">
            this.set('label', 'Clicked');
        </script>
    </button>
</form>

Answer №2

Check out the dojo/_base/event#stop method; for more information, you can visit the documentation here. The emphasis is mine:

This function prevents event propagation and overrides the default action

You can add this to your code.

require(['dojo/_base/event']);

<button dojotype="dijit.form.Button">
    <asp:Label ID="lblClear" runat="server" meta:resourcekey="lblClearResource1" />
        <script type="dojo/method" event="onClick" args="evt">
                dojo.stopEvent(evt); // dojo/_base/event extends dojo pre-2.0 
                return ClearCheckBoxes('<%=clientIds.ClientID%>');
        </script>
</button>

dojo/_base/event#stop is compatible with all browsers, including (as far as I know) IE8.

If it's not possible to load modules like that in your templates (which I haven't personally tried), here's a specific code snippet for preventing default behavior in IE:

evt = evt || window.event;
evt.cancelBubble = true;
on._preventDefault.call(evt);

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

Using Javascript/JQuery to apply pixel values in CSS styling

Recently, I've come across a discrepancy between two different ways of accessing CSS properties in jQuery: <foo>.css('marginTop') (which I always assumed was the standard notation) and <foo>.css('margin-top') (which ...

"Utilizing NodeJs with Mongoose for handling promises using the then/c

Encountered an issue with Mongoose promises MyModel.find().then((data)=> Promise.reject()) .catch(()=>console.log('first catch')) .then(()=>console.log('ok')) .catch(()=>console.log('second catch&a ...

How to fix the Uncaught TypeError: Unable to access the 'open' property of an undefined value in the AppBar + Drawer component with ReactJS and Material-UI?

I'm currently working on implementing the navigation feature in my app using Material-UI framework. I want the default hamburger icon on the left side of the AppBar to open the Drawer component when clicked. However, I keep encountering an error that ...

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error ...

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

Angularjs changes the "&" character to "&"

Here is the AngularJS code I am using: $scope.getEventSeconds = function(){ $http.get('myfile.php', { params: { 'action': 'get_datas' } }).success(function(data){ $scope.list = data; $scop ...

After a postback in JavaScript, the Root Path variable becomes null

I have been attempting to save the Root URL in a JavaScript variable within my _Layout.cshtml like this: <script type="text/javascript> var rootpath = ""; $(document).ready(function () { rootpath = "@VirtualPathUtility.ToAbsolute("~/ ...

How to Generate an Array of JSON Objects in JavaScript on a Razor Page using a Custom ViewModel in MVC?

Attempting to populate the array within my script for future charting with D3.JS, I came across some issues. Following advice from this post, I used a specific syntax that unfortunately resulted in an error stating "Uncaught ReferenceError: WebSite is not ...

Unable to hear sound on Mozilla Firefox

I am facing an issue with playing an audio file using the audio tag inside the body element. The audio plays perfectly in Chrome once the body has finished loading, but it fails to play in Mozilla Firefox. I even attempted to download the audio file and pl ...

Trigger a callback in KnockoutJS once all bindings have been successfully set up

I am facing a frustrating bug that is detailed here: <select> only shows first char of selected option and I am looking for a solution to remove the display:none from my select boxes in order to resolve this issue. Any ideas? Here's the binding ...

I am looking to load an alert message simultaneously with loading an HTML link

My request is for a pop-up sweet alert to appear when the "accept your promotion" button is clicked, along with calling a relevant link at the same time. This link will update a data column in a database based on Boolean values. <script src="https://cd ...

JavaScript reference problem when copying

Initially, I create a raw array by using the following initialization: $scope.rawUsers = angular.copy($scope.users); Subsequently, I make modifications to the data like so: function filterUsers(searchString, onlyMine) { $scope.users = []; _.find($scop ...

Encountering a timeout error while using selenium-webdriver and phantomJS

Currently, I am developing my automated test scripts using a combination of selenium-webdriver, phantomJS, and mocha. The script I am working on is written in JavaScript. One requirement is to wait until a specific element becomes completely visible befo ...

Selenium WebriverJS does not support right mouse button clicks in PhantomJS

Currently, I am utilizing Selenium in combination with WebdriverJS to automate a straightforward web application. However, an issue arises when transitioning from Chrome to PhantomJS, resulting in the test not functioning as intended. Specifically, the rig ...

Modify the color of the text box using a CustomValidator

When dynamically creating text boxes, I want to change the color of a text box if it is left blank and the user submits the form. In the .aspx.cs file, I am using the code behind approach and have written the following code for the textBoxObj, which is th ...

Issue with exporting Three.js to Maya

I've been attempting to utilize the Three.js exporter for Maya found here. However, when I try to load the threeJsFileTranslator.py plug-in from the plug-ins manager in Maya, I encounter an error in the Script Editor: // Error: line 1: invalid synta ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

Does anyone have insight on which JavaScript library is being utilized in this context?

While perusing an interesting article, I came across an image that caught my attention. Clicking on it revealed a unique way to view the full size. I am curious if anyone knows which JavaScript library was used for this effect. You can find the article her ...

Mongoose fails to persist data

Exploring the world of Express and following a tutorial to create a project. Currently stuck in the seeding phase where I am trying to populate my database with data. However, when I execute the command node product-seeder.js in the terminal, no data is be ...

Custom filtering in Angular using ngTables is an advanced feature that allows

I am currently working on implementing custom filtering in ngTables, similar to this example. I have a set of columns with standard text input filters, but for some of them, I want to utilize my own filtering function instead of the default angular $filter ...