Search code examples
javascriptdiscorddiscord.js

How do i get the value of a select menu after pressing a button? (discord.js)


I have a message with 2 action rows. One contains a select menu, and the other contains a button. How do i get the selected item from the select menu when the button is pressed?

I have this following code so far:

if (interaction.isButton()) {
        if (interaction.customId == 'deleteTask') {
            console.log("Deleting task!")
            console.log(taskName)
            delete(taskName)
        }
 }

I need the variable taskName to be the selected option in a select menu. The select menu is in the same message as the button, and it has the custom Id 'selectTask'. This is the code for the select menu and button menu:

const row = new MessageActionRow() // Define action row
            .addComponents(
                new MessageSelectMenu() // Add task selector
                    .setCustomId('selectTask')
                    .setPlaceholder('Select an assignment..')
                    .addOptions(choices),
            );

const btnrow = new MessageActionRow() // Define action row
            .addComponents(
                new MessageButton()
                    .setCustomId('deleteTask')
                    .setLabel("Delete task")
                    .setStyle("DANGER"),
            );

Solution

  • If you already have a message component collector you just need to get the first value from that collector. Docs: https://discord.js.org/#/docs/discord.js/stable/class/SelectMenuInteraction?scrollTo=values

    collectorInteraction.values[0]
    

    Change collectorInteraction to whatever you named your collector parameter

    If you still need to make a component collector, maybe visit these 2 websites: https://discord.js.org/#/docs/discord.js/stable/class/InteractionCollector

    https://discordjs.guide/popular-topics/collectors.html#message-collectors