Skip to content

Can MultiSelect provide a maximum selection limit feature? #331

@jerrybaxia

Description

@jerrybaxia

For example, when the maximum number of selections is reached, users can't select more items unless they first deselect some of their current choices.

// ==============================================
// Limit maximum selections
// ==============================================
let max_selections = 2; // Set maximum number of selections
loop {
    let selections = MultiSelect::with_theme(&ColorfulTheme::default())
        .with_prompt("Select your favorite foods (max 2 items)")
        .items(&foods[..])
        .defaults(&defaults[..])
        .max_length(2)
        .interact()
        .unwrap();

    if selections.len() <= max_selections {
        // Process valid selections
        if selections.is_empty() {
            println!("You didn't select any food :(");
        } else {
            println!("You selected:");
            for index in selections {
                println!("  - {}", foods[index]);
            }
        }
        break;
    } else {
        println!("You can select at most {} items. Please try again.", max_selections);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions