The onsubmit event in Javascript activates the parent's onclick event

On my HTML page, I have a table with a form in each row. Clicking on the row should open a detail page, but clicking within the form should not trigger this action.

Here is an example of what my row looks like:

<tr onclick="window.parent.location.href='details.php?id=123';"><td><img /></td><td>text</td><td>price<br>
  <form method="post">
    <input type="number" name="size" value="1">
    <input type="submit" onsubmit="return confirm('Are you sure?');">
  </form>
</td></tr>

The desired behavior is that if I click in the size field or on the submit button, the detail page should not be called.

I have researched and found that event.stopPropagation() can be used for this purpose, but I am struggling to implement it using plain JavaScript. It seems like there should be a straightforward solution, but I haven't been able to figure it out yet.

Answer №1

Give it a shot

<tr onclick="window.parent.location.href='details.php?id=123';">
    <td><img /></td>
    <td>text</td>
    <td>price<br> 
        <form method="post" onsubmit="return confirm('Are you sure?');"> 
            <input type="number" name="size" value="1" onclick="event.stopPropagation()"> 
            <input type="submit" onclick="event.stopPropagation()"> 
        </form> 
    </td>
</tr>

Note: Make sure to remove the onsubmit attribute from the input element and add it to the form element instead. Thanks to @epascarello for pointing out this correction.

Answer №2

Below is the correct answer

<tr onclick="var x = event.clientX;var y = event.clientY;if(document.elementFromPoint(x, y).tagName.toLowerCase()!='input'){window.parent.location.href='details.php?id=123'; }"><td><img /></td><td>text</td><td>price<br>
  <form method="post">
    <input type="number" name="size" value="1">
    <input type="submit" onclick="return confirm('Are you sure?');">
  </form>
</td>
</tr>

Answer №3

I recently faced this issue myself and found a helpful post on it: How to prevent event propagation from parent div to child div

Here is a suggested solution:

var parent = document.getElementsByClassName("parent")[0];
var child = document.getElementsByClassName("child")[0];

parent.addEventListener("click", function(e) {
  alert("you clicked parent"); 
  if (e.target !== this) {
    return;
  }

  e.stopPropagation();
});

child.addEventListener("click", function(e) {
  alert("you clicked child"); 
  if (e.target !== this) {
    return;
  }

  e.stopPropagation();
});
.parent {
  width: 500px;
  height: 500px;
  background-color: red;
}
.child {
  width: 200px;
  height: 200px; 
  background-color: blue;
}
<div class="parent">
  <div class="child">
    
  </div>
</div>

If you want better readability, consider using a script with onclick element properties like so:

<tr onclick="changeLocation(e, 'details.php?id=123')"><td><img /></td><td>text</td><td>price<br>
  <form method="post">
    <input type="number" name="size" value="1">
    <input type="submit" onclick="return confirm('Are you sure?');">
  </form>
</td></tr>

<script>
function changeLocation(e, reference) {
      if (e.target !== this) {
        return;
      }

      e.stopPropagation();

    window.parent.location.href=reference;
}
</script>

You can also create a propagation event function for better handling:

<tr onclick="stopProp(this); window.parent.location.href='details.php?id=123';"><td><img /></td><td>text</td><td>price<br>
  <form method="post">
    <input type="number" name="size" value="1">
    <input type="submit" onclick="stopProp(this); return confirm('Are you sure?');">
  </form>
</td></tr>

<script>
function stopProp(e) {
      if (e.target !== this) {
        return;
      }

      e.stopPropagation();
}
</script>

Answer №4

Appreciation to everyone - I successfully implemented the approach suggested by sanketd617 and it performed as expected - my apologies for the oversight with the placement of onsubmit - in my actual code, it belongs within the form tag - I manually typed it out instead of copying and pasting since my code is a bit intricate.

I also experimented with Aricha's code but unfortunately, it did not yield the desired outcome for me - it still redirected to the detail-page, perhaps I made an error there as well. Similar attempts in the past have also fallen short for me.

However, the straightforward solution utilizing onclick="event.stopPropagation()" within the input elements' onclick attribute escaped my notice until now. Much thanks for shedding light on this.

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

A straightforward method of transmitting data from JavaScript to the Python back-end within a Streamlit application

Utilizing the st.components.v1.iframe, I integrated an authentication system that sends a token back to the parent when a user is authenticated. The iframe content is as follows: <script src="remote/auth.js"></script> <scri ...

Convert my information to an XML document

Successfully, I have loaded the content of an XML file into my PHP document using the following method: $(document).ready(function () { $.ajax({ type: "GET", url: "abstimmer.xml", dataType: "xml", success: function ...

I am having trouble grasping certain syntax in JavaScript when it comes to using `${method_name}`

I'm having trouble understanding some of the syntax in this code, particularly ${method_name}. I'm not sure what we are achieving by passing the method name within curly braces. global._jsname.prototype.createEELayer = function (ftRule) { if ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

Error message stating 'compression is not defined' encountered while attempting to deploy a Node.js application on Heroku

Why is Heroku indicating that compression is undefined? Strangely, when I manually set process.env.NODE_ENV = 'production' and run the app with node server, everything works perfectly... Error log can be found here: https://gist.github.com/anony ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

Utilizing C in WebAssembly to return string values

Is it possible to retrieve a JavaScript string from a WebAssembly function? https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not functional C #include <stdio.h> #include <string.h> void jsPrintString(const ch ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

Getting data from a latin1 (iso-8859-1) database using javascript/nodejs: Tips and Tricks

My ancient mysql database (mysql 5.0.2) is in latin1 format and I'm encountering an issue with getting data from it. Non-ascii characters such as Â, À, and Á are appearing as 'ef bf bd' in hex, which means different characters are being d ...

Issues arise when the Slick functionality fails to load following an ajax request

I've come across a situation similar to the one on this post. I'm having trouble getting my slick carousel to work after a successful ajax call. Despite trying all the solutions provided, it's still not functioning as expected. The code for ...

Ruby on Rails slider bar functionality

Currently, I am developing a video-focused application using Ruby 1.9.2 and Rails 3.1. One of the key features I need to implement is a slider bar that allows users to adjust the total duration of a video in real-time. Despite my attempts to use HTML5 fo ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

Leveraging the power of react routes for efficient navigation within a react-based application

I am currently facing an issue with setting up routes for a basic react application using react-router. The given routes don't seem to match and the switch defaults to displaying the 404 page. Below is the code for the routes: import { BrowserRout ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

Count duplicated values in an array of objects using JavaScript ES6

I am working on creating a filter for my list of products to count all producers and display them as follows: Apple (3) I have managed to eliminate duplicates from the array: ["Apple", "Apple", "Apple"] using this helpful link: Get all non-unique values ...

Utilizing ng-style with a ForEach loop on an Object

How can I dynamically add a new style property to objects in an array in Angular, and then use that property inside ng-style? CommentService.GetComments(12535372).then(function () { $scope.comments = CommentService.data(); angular.forEac ...

Repairing a syntax error in a jQuery selector variable

$(".className").click(function(){ var link = $(this).find("a").attr('href'); //output is '#myID' var findItems = $(link '.mydiv').length; //WRONG var findItems = $(link + '.mydiv').length; ...

What is the method for enlarging an element without regard to surrounding elements?

I am working on a code where I want the element to zoom in when hovered, completely disregarding its normal flow. By "ignoring its flow," I mean that other elements like tags might obstruct parts of its content. https://i.sstatic.net/NBoez.png https:// ...