When a td element is clicked, the Textbox will also be clicked

Similar Question:
Dealing with jQuery on() when clicking a div but not its child

$(oTrPlanning).prev().children('td').each(function () {
    this.onclick = setCountClick;
});

When a TD element is clicked, the function setCountClick() is executed. However, if the TD contains a Textbox:

<td> 
    <input class="Input-InlineFilter" id="TextFirst"  type="text" value="">
</td>

Therefore, when inputting text into the Textbox, setCountClick() is called again. The desired behavior is to only call setCountClick() when clicking the TD, but not the Textbox.

Answer №1

When a click event occurs, it travels up the DOM hierarchy from the textbox to the td, all the way to the body. If you want to prevent clicks on the textbox from triggering the td click handler, you should stop the event from bubbling:

$('#TextFirst').click(function (e) {
    e.stopPropagation();
});

Check out the documentation for stopPropagation

To optimize your code, consider utilizing this bubbling behavior by attaching only one event handler for all td elements:

// attach one handler to all tds
$(oTrPlanning).prev().on('click', 'td', function (e) {
    // verify that the clicked element is a TD
    if (this.nodeName === 'TD') {
        setCountClick(e);
    }
});

More information about nodeName

If the use of the this keyword within the setCountClick function becomes problematic, consider using $.proxy or bind when calling setCountClick:

setCountClick.bind(this)(e);

bind creates a new function where the argument passed becomes the current context indicated by this. This allows you to execute the function with the desired context and parameters.

Learn more about the bind method

Answer №2

An issue arises with the event propagation from child elements to parent elements. A solution involves binding events in the following manner:

$(oTrPlanning).prev().on('click', 'td', setCountClick);

The setCountClick method will take the event as its first parameter, which can be examined as shown below:

function setCountClick(event) {  
   // Check if the click occurred on a TD element
   if ($(event.target).is('td')) {
        // Code to execute when a TD is clicked
   }
}

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

Angular's UI router is directing users to the incorrect URL

Just starting out with Angular 1 and tasked with adding a new feature to an existing webapp. The webapp utilizes jhipster for backend and frontend generation (Angular 1 and uirouter). I attempted to create my own route and state by borrowing from existing ...

Generate an HTML webpage with dynamic content using MySQL

How can I display data from a MySQL table on an HTML page? The content in my table includes various rows that I would like to show separately on the web page. This is the structure of my table: I envision the web page layout to showcase each row individ ...

There seems to be an issue with your SQL syntax that is preventing the data from being entered correctly into the database using Node.js, MySQL, and Express

After successfully displaying data from my database, I attempted to add data to it using the following code snippet: exports.tambahData = (req, res) => { var keyy = req.body.keyy; var valuee = req.body.valuee; var brand = req.body.brand; ...

Styling elements conditionally in React JS using inline styles

If the status of this task is 'Completed', I would like to hide the button (similar to adding a display: none property). Code: <Button size="small" style={{display:this.state.task.status == "Completed" ? "none":""}} ...

Replace Euro symbols in JavaScript Regexp with grouping

Need assistance creating a Regex pattern for &#8203; € 14,50. After the replacement is completed, only 14,50 Can anyone provide guidance? ...

Struggling to use GSAP to control the timeline with my custom functions

I'm attempting to create a greensock animated banner with the ability to switch between different scenes. I've made progress by setting up the timeline for each scene's intro and outro animations using the GreenSock API documentation. Howeve ...

Aligning a grid container in the middle

#panelb { background: lightblue; display: grid; grid-template-columns: repeat(auto-fit, 300px); } .card { background: gold; } .imgcard { display: block; width: 100%; margin: 0 auto; } <div id='panelb'> <div class=' ...

Simultaneous activation of CSS classes by multiple RouterLinkActive components

Using multiple <a> tags with routerLink presents a unique behavior. Upon loading the home page, the home icon in aMenuItems is correctly given the active class through routerLinkActive, while the remaining elements in the array do not have this class ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

encountering issue alerts when using the MUI TextField module alongside the select function

Encountering an error in the MUI console: children must be provided when using the TextField component with select. <TextField select id="outlined-basic" label="User Name" name="user" size="small" {...teamForm.getFieldProps("user")} erro ...

Ways to calculate the total number of keys within a JSON object at a certain level

I need to process a JSON file by extracting values from keys located at a specific depth. The initial value I want to access is situated here: json.children[0].children[0].children[0] Is there a method to navigate through the JSON object at a particular ...

Show individual row information within a bootstrap modal upon clicking the edit button

As a beginner in programming, I am attempting to use bootstrap modal to showcase row data from a mysql table within the modal window. Following the advice found on stackoverflow regarding "Pull information from mysql table to bootstrap modal to edit" didn ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

How are jQuery.ajax and XMLHttpRequest different from each other?

My goal is to fetch and run the script contained in a file named "example.js" using an AJAX request. Suppose the content of example.js looks like this: const greetings = { hello: "Hello", goodBye: "Good bye" } console.log(greetings.hello) In anot ...

Change the output of Object.fromEntries

I've been working on updating the values of an object using the .fromEntries() method. The issue I am facing is that even though I am returning a modified Array of hours, when the function completes it reverts back to the original complete Array. If ...

Having trouble with testing axios web service promises to return results using Jest in a Vue.js application

In the process of developing a new application with Vue.js and axios, I am focusing on retrieving stock market details based on company names. To kickstart the application, I am compiling all the names of US-based S&p 500 companies into a JavaScript ar ...

What's the best way to vertically center a div with a 100% width and a set padding-bottom on the screen?

I am struggling with positioning the following div on my webpage. .div { width:100%; padding-bottom:20%; background-color:blue; } <div class="div"></div> I have been searching for a solution to vertically center this responsive div on my web ...

Continuously invoking a function until jQuery's .post method has completed loading

As I am diving into the world of jQuery framework, I encountered a situation where I used the readyState() function while working with AJAX in regular JavaScript to display a loading gif image. However, when transitioning to using jQuery's .post() met ...

Initiate a click action upon receiving a focus event

I can't seem to figure out why this code is not functioning as expected: $('a').focus( function() { $(this).click(); }); Context: I am working on developing a form where navigating through different elements (such as textboxes) will au ...

Only one specific SVG tag is affected by the CSS stylesheet

I'm encountering an issue with my web page that has multiple SVG tags. Each SVG tag includes a block of style tags containing CSS styles for the respective SVG element. The problem is that these styles seem to leak into the overall global styles. For ...