Skip to main content
Participant
May 7, 2024
Answered

Show/Hide Layers Using a Dropdown Menu

I have a base layer that I want to remain visible, but I would like to switch between the rest of my layers by using a dropdown menu. I'm trying to write it such that when one layer is selected, the rest are hidden. This is what I have so far, but when I select anything from the dropdown, nothing changes.

 

// Define the layer names
var layerNames = ["Emergency Repair", "CSA Visit", "Installation", "Other"];

// Function to toggle layers based on dropdown selection
function toggleLayers() {
var selectedOption = event.target.value;
for (var i = 0; i < layerNames.length; i++) {
var layer = this.getOCGs()[layerNames[i]];
if (layer) {
if (layerNames[i].replace(/\s+/g, '') === selectedOption) {
layer.state = !layer.state;
} else {
layer.state = false;
}
}
}
}

// Add an event listener to the dropdown
this.getField("Dropdown2").setAction("Keystroke", "toggleLayers()");


Apologies if this code looks weird. I've resorted to asking ChatGPT for help.

This topic is closed to new replies. Start a new post to keep the conversation going.
try67
try67Correct answer
Community Expert
May 8, 2024

Yeah, I was going to ask you about that... Just use this:

 

var layers = this.getOCGs();
for (var i in layers) {
	layers[i].state = layers[i].name=="Guides and Grids" || (layers[i].name==event.value);
}

6 replies

Amal.
Legend
May 7, 2024

Hi there

Hope you are doing well and thanks for reaching out.

The workflow you are trying to achieve might be possible using JavaScript. For more information, please check the help pages listed below:
https://acrobatusers.com/tutorials/javascript_console/
https://helpx.adobe.com/acrobat/using/applying-actions-scripts-pdfs.html

Hope it will help

Regards
Amal

Translate
try67
Community Expert
Community Expert
May 7, 2024

Get rid of all the other code, and use this as the drop-down's custom Validation script:

 

var layers = this.getOCGs();
for (var i in layers) {
	layers[i].state = (layers[i].name==event.value);
}
Translate
Participant
May 8, 2024

Good grief. I knew the code should be short, but I didn't think it would be quite that short. That's taken care of a large portion of things, but the background layer (Named "Background and Title") disappears when I use this. Any thoughts?

Translate
try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
May 8, 2024

Yeah, I was going to ask you about that... Just use this:

 

var layers = this.getOCGs();
for (var i in layers) {
	layers[i].state = layers[i].name=="Guides and Grids" || (layers[i].name==event.value);
}
Translate
try67
Community Expert
Community Expert
May 7, 2024

> I've resorted to asking ChatGPT for help.

That's your main issue. This code contains a lot of errors.

Translate