Executing an onEdit script exclusively on specific sheets

As a beginner in coding Scripts, I have successfully managed to modify a script that adds a custom timestamp onEdit. It inserts the timestamp into the cell next to where the edit occurred, targeting columns 3 and 6 with an offset of -1.

The workbook now consists of multiple sheets, but the current script is not suitable for all of them. I am struggling to specify which sheets it should run on.

I have put together the following script, which works across all sheets, but I now need to limit it to specific sheets:

function onEdit(e) {
 var colsToWatch = [3,6],
    offset = [-1,-1],
    ind = colsToWatch.indexOf(e.range.columnStart);
if (ind === -1 || e.range.rowStart === 1) return;
e.range.offset(0, offset[ind])
.setValue(!e.value ? null : Utilities.formatDate(new Date(), "GMT+1", "dd MMM yyyy     HH:mm.ss"))
}

I would greatly appreciate if someone could provide me with the code to enable the script to only run on specific sheets. Additionally, suggestions for a simpler script that achieves the same objective, without overwriting the timestamp if the cell is edited again, would be very helpful.

Thank you so much!

Answer №1

function onEdit(e) {
  const sh = e.range.getSheet();
  const shts = ['Sheet1','Sheet2'];
  const idx = shts.indexOf(sh.getName());
  if(~idx ) {
    //Only execute this code on Sheet1 or Sheet2
  }
}

My preferred solution (for Sheet1 and Sheet2):

function onEdit(e) {
  //e.source.toast('entry');
  const sh = e.range.getSheet();
  const shts = ['Sheet1','Sheet2'];
  const idx = shts.indexOf(sh.getName());
  if(~idx ) {
    let rg = sh.getRange(e.range.rowStart,9);
    if(rg.isBlank()) {
      rg.setValue(new Date());
    }
  }
}

Check out the JavaScript Reference for more information

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

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

Executing a Google Script will result in a newly inserted column automatically adopting the

My coding issue involves a simple scenario where cell A1 contains a date, for example 06/06/2017. What I aim to do is add three columns and apply formulas to them. I insert columns using the following code: ss.insertColumns(1,3); Subsequently, I set for ...

Is there a way to prevent Chrome from automatically toggling into debug mode?

When the debugging window is open, the debugger seems to start running through lines automatically without any breakpoints being set. I attempted to use the "Deactivate breakpoints" button, but it had no effect whether it was enabled or disabled. This is ...

Click to add a card

Attempting to incorporate a new row with the click of a button dynamically has proven to be challenging for me. As someone who is relatively new to JavaScript, I am struggling to figure it out. In the demonstration provided below, you will notice that noth ...

Troubleshooting a potential JSON problem when linking Angular JS with Firebase

My current challenge is figuring out how to properly format firebase data to work seamlessly with Angular. I have a functional view that works with ng as a static display, and within the $scope it is defined like this: $scope.standardItems = [{ name: ...

Implement a fadeout effect by using a timeout function that adds a class to the div element in

I implemented a loader on my webpage that animates for 3 seconds before a function kicks in to modify the styles and make it invisible. I am looking to add a fadeout effect when the 'waa' style is applied to the 'load' div. setTimeou ...

Stop the default behavior of a link based on the Ajax response

A controller has been created in Magento to check if there are any products in a list. If products exist in the list, it will return true; otherwise, it will return false. The front-end below triggers an ajax call. It must remain a link and cannot be chan ...

Adjust the stroke and fill colors of an SVG element when hovering over it

I am facing a challenge with an SVG image that I have: https://i.stack.imgur.com/r4XaX.png When hovered over or clicked, it should change to https://i.stack.imgur.com/EHRG2.png Current Icon <svg width="24" height="24" viewBox="0 0 24 24" fill="non ...

Is there a way to only allow the active video to play while disabling the others in this Vue 3 and Bootstrap 5 carousel?

I'm currently developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Additionally, I'm incorporating Bootstrap 5 for the UI. To showcase movie trailers on the movie details page, I've created the ...

Tips for locating the index of an object within an array by validating property values in JavaScript

My array looks like this: $scope.myArray = [{ columnName: "processed1", dataType: "char" }, { columnName: "processed2", dataType: "char" }, { columnName: "processed3", dataType: "char" }]; I'm trying to locate the index of an object wher ...

Integrating React with the math.js library for enhanced functionality

My React component is having trouble integrating with the math.js library. When I attempt to display the output of the code in the console, everything works fine without resetting the state. However, when I try to use the result of the evaluate() function ...

Create a variable in Angular to determine the selected array

I have a JSON array and I am displaying the items in a select element. When an item is clicked, a new select is generated for any subarray items. If you follow this link, you can see exactly what I mean. Everything is working well so far, but I'm ha ...

The nullish coalescing operator in JavaScript is running code on both of its sides

console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist'); console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exis ...

Exploring Nashorn's Global Object Variables Through Access and Intercept Techniques

I recently came across a question called "Capturing Nashorn's Global Variables" that got me thinking. I'm facing limitations when it comes to capturing the assignment of variables to the global object. For example, let's say I evaluate the ...

Eliminate all blank spaces at the top and bottom of Span by squishing it

Imagine I have this code snippet: <span class="labels" style="background-color: #FFFFFF;border: 1px solid #000000;font-family: Verdana;font-size: 11px; ">74.58 ft.</span> I am looking for a way to compress the span element so that only the te ...

Troubleshooting issue in App component while utilizing React-Redux's 'connect' function

Upon attempting to utilize the connect() function provided by react-redux, I encountered the following error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the r ...

What is the method for altering the appearance of grid columns with javascript?

What modifications do I need to make in JTML and Javascript? var opac; function checkfun() { opac=(Array.from(document.querySelectorAll('input[type="checkbox"]')) .filter((checkbox)=>checkbo ...

By using .innerHTML to create an element, the validation of HTML form fields can be circumvented

After inserting a form field with standard HTML validation constraints (pattern & required), using the .innerHTML property does not trigger validation. While I understand the difference between creating an element with .innerHTML and document.createElement ...

Unable to access the current state within an asynchronous function in React.js

I have encountered an issue with updating state in the top-level component (App) and accessing the updated state in an asynchronous function defined within useEffect(). Here are more details: The problem arises when I try to retrieve the state of the cons ...

When dynamically binding onclick events within a for loop, all buttons end up with the same value

I'm currently working on a project where I am creating buttons dynamically and assigning an alert function for each one upon a click event. Here is the JavaScript function: function GenerateButtons(tabObj) { for (var t = 0; t < tabObj.views.vie ...