Access a webpage programmatically by utilizing a checkbox and embedding a script

I am trying to create a script in Google Sheets that will automatically open a URL when a checkbox is checked within the same row. The checkboxes are located in cells A3:A and their corresponding URLs are in cells C3:C.

See the correct output here

Output for the project:

Checkbox URL Opener Script

The current script only opens the first cell with a checked checkbox:

function processSelectedRows() {
  var rows = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("n-gadget").getDataRange().getValues();
  var headers = rows.shift();
  rows.forEach(function(row) {
    if(row[0]) {
      Logger.log(JSON.stringify(row));
      setCellColors();
      openURL();
    }
  });
}

function setCellColors() {
  // Accessing the sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("n-gadget");
  
  // Getting values from specified range
  var range = sheet.getRange("A1:A");
  var rangevalues = range.getValues();

  // Loop through the results
  for (var i in rangevalues) {
    for (var j in rangevalues[i]) {
      var x = parseInt(j, 10) + 1;
      var y = parseInt(i, 10) + 1;

      // Applying rules logic
      if (rangevalues[i][j] == 1) {
        sheet.getRange(y,x).setBackground("green");
        sheet.getRange(y,x).setFontColor("white");
      }
    }
  }
}

function openURL(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("n-gadget");
  var link = sheet.getRange("C3:C").getValue();
  var title = sheet.getRange("B3:B").getValue();
  showAnchor(title,link);
}

function showAnchor(name,url) {
  var html = '<html><body><a href="'+url+'" target="blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
  var ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui,"Check Stats");
}

Answer №1

I have just found the solution:

let link = sheet.getRange(y, x+2).getValue();
let title = sheet.getRange(y, x+1).getValue();

Below is the complete code (The data validation only accepts 1 and 0 instead of TRUE or FALSE):

function processSelectedRows() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = ss.getSheetByName("n-gadget");
  let rows = SpreadsheetApp.getActiveSpreadsheet().getDataRange().getValues();
    let headers = rows.shift();
  rows.forEach(function(row) {
    if(row[0]) {
      Logger.log(JSON.stringify(row));
      setCellColors();
    }
  });
}

function setCellColors() {
  //Access the specific sheet you want to work with. 
 let ss = SpreadsheetApp.getActiveSpreadsheet();
 let sheet = ss.getSheetByName("n-gadget");
  //Retrieve the entire range and necessary values from it.
 let range = sheet.getRange("A1:A");
 let rangevalues = range.getValues();
  
 for (var i in rangevalues) {
  for (var j in rangevalues) {
   //Determine the current cell's location by row and column index
      let x = parseInt(j, 10) + 1;
      let y = parseInt(i, 10) + 1;

       if (rangevalues[i][j] == 1) {
        //Adjust cell formatting
        let link = sheet.getRange(y, x+2).getValue();
        let title = sheet.getRange(y, x+1).getValue();
       
        sheet.getRange(y, x).setBackground("green");
        sheet.getRange(y, x).setFontColor("white");
        showAnchor(title, link);
        range.clear();
      }
   }
  }
}

function showAnchor(name, url) {
  let html = '<html><body><a href="'+url+'" target="_blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
  let ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui, "check stats");
}

view the output here

P.S. There are still some loopholes like handling multiple checkbox selections (added the range clear function), so I am open to suggestions and improvements.

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

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Tips for retrieving the ID field from a JSON-encoded result

After calling a function, I received the following result: json_encode(searchpage) Result : [{"category":"Hospital\/clinic","name":"\u05d1\u05d9\u05ea \u05d0\u05d1\u05d5\u05ea \u05e9\u05dc\u05de&bs ...

Once more: "The JSON object should be a string, bytes, or bytearray, not a list" encountered in the requests library

I'm struggling with a simple request and can't figure out what's wrong data1 = df.loc[N, 'online_raw_json'] print(type(data1)) print(data1) data1 = json.dumps(data1) print(type(data1)) print(data1) response = requests.post("h ...

Unlocking the secrets of extracting information from deeply nested JSON files

Struggling to grasp how to retrieve values from the nested JSON file format of TheMovieDB API for my University assignment. Trying to work with this specific file: This is what I have so far: httpConnect jParser = new httpConnect(); String json = jPar ...

Developing a compressed file in JavaScript

async purchaseMultiple(decoded, purchaseData){ const user = await Database.user.findOne({where: { id_user: decoded.id_user }}); if( ! user) return [404, 'ERROR: User [' + decoded.id_user + '] not found']; if(user.credi ...

Split total based on checkboxes toggled with JavaScript

I'm facing a challenge. I have a total sum of donations collected, for example, 10€. Additionally, there are various NGOs that one can select to donate to. Individuals have the option to toggle on/off which NGO's they wish to contribute toward ...

An issue arises when trying to execute the JSON code as it refuses to convert

It seems like I am having trouble converting the API data into a C# object. Surprisingly, my IDE is not showing any errors, but when I try to run it, an error occurs. using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using ...

Publish a Reddit comment using programming code

I've been attempting to automate the process of posting a comment on Reddit using the Snoocore library. Below is the code I'm working with: function postComment() { var commentText = document.getElementById("response").value; ...

Using jQuery to Extract Data from an External JSON Source

I am working with a large 2 MB JSON object that I need to parse using jQuery. The entire object has been saved in a file called "timeline.js", and I am looking to extract specific records from it as required. Originally, my dataset was in XML format, but ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Tips for populating web view fields on Android using a combination of Java and JavaScript

Encountering an issue while attempting to populate fields in my android web view. Consistently receiving this error message 01-28 05:06:22.980: E/Web Console(2827): Uncaught TypeError: Cannot set property 'value' of null at null:1 Despite search ...

Unable to retrieve the numerical value within the chart

I am a beginner in learning angularjs. I have implemented a contextmenu for displaying table data. <div contextmenu-container="meta.contextmenu"> <table class="table table-striped table-bordered report-table" fixed-header> ...

The magic of JQuery DataTables

I am a beginner in jQuery and I have recently implemented Datatables in my grid. However, I encountered an issue where the info bar at the bottom of the jQuery data tables is not displaying as intended: see image here My goal is to show the first entries ...

Distributing the event object without the use of jQuery

Sorry for the basic question. It's been a challenge to find information on JS event handling without running into jQuery examples. I'm focused on DOM manipulation using pure Javascript to gain a deeper understanding of browser functionality. I w ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

jQuery failing to append code after being removed

I need some assistance with an issue I've run into while using jQuery's .remove(). Here is a snippet of code that showcases the problem: $( '.video-button span.glyphicon-play' ).click(function() { $( '#video-player' ).ap ...

Using .done(), .then(), and .when() in jQuery for sequencing ajax requests in a specific order

After diving into the world of Promises in jquery and trying to avoid "callback hell" when dealing with multiple ajax requests, I still find myself without a clear answer on which method to use - whether it's .done(), .then(), or .when() - for chainin ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

Using HTML and CSS to generate an alpha mask on top of an image

I am currently working on a website and I am looking to create an effect where an image is masked by an overlay. The goal is to achieve a "fade out" effect, without any actual animation, but rather make it appear as if the image is gradually fading into th ...

The discrepancy between the ng-model value in the controller and the input field in the HTML

In my HTML code, I have an input field that is linked to a specific value using the ng-model attribute. Initially, any changes made to this ng-model in the controller are accurately reflected in the input field. However, when I manually type something into ...