The dropdown menu in Svelte is malfunctioning when only one option is available

One issue I am facing in my Svelte application is with a dropdown menu that displays a list of players. I am trying to implement a search functionality where the dropdown menu should only show players that match the search query. However, I have encountered a problem - when there is only one player that matches the search query, I am unable to select that player from the dropdown menu even though it displays correctly. How can I resolve this issue?

Player Selection

<select class="form-select" bind:value={player_id} id="player">
     {#each players as player}
          {#if !tournament.players.includes(player._id) && player.name
               .toLowerCase()
               .includes(searchTerm.toLowerCase())}
                    <option value={player._id}>{player.name}</option>
          {/if}
      {/each}
</select>

Search Bar

<input class="rounded line"
 type="text"
 bind:value={searchTerm}
 placeholder="Search for a player"
/>

Update Button

<button class="btn btn-primary line"
 on:click={addPlayerToTournament}>Update
</button>

UPDATED Function to Add Player to Tournament

function addPlayerToTournament() {
    tournament.players.push(player_id);
    tournament.players = tournament.players;
    axios
        .put(
            "http://localhost:3001/api/tournaments/" + tournament_id,
            tournament
        )
        .then((response) => {
            getTournament();
        });
}

I have attempted to use the includes method to check if the player's name is included in the search term, and then implemented an if statement to display only the players that meet this condition in the dropdown menu.

Any assistance or suggestions on how to tackle this issue would be greatly appreciated.

Answer №1

I am truly grateful to @Corrl for their invaluable assistance and dedication in providing a solution that has allowed me to progress with my project. Their contributions have been instrumental in helping me achieve my goals. Below is the successful solution that I implemented. Feel free to reach out if you have any queries.

Code Block

<script>
let searchTerm = "";
let selectablePlayers = [];

$: calculateSelectablePlayers(searchTerm, tournament)

function calculateSelectablePlayers(searchTerm, tournament) {
        console.log('calculate - only runs if searchTerm or tournament changes')
        if(searchTerm || tournament.players.length > 0) {
            selectablePlayers = players.filter(player => {
                const notYetInTournament = !tournament.players.includes(player._id)
                const searchTermInName = player.name.toLowerCase().includes(searchTerm.toLowerCase())
                return notYetInTournament && searchTermInName
            })
            if(searchTerm) player_id = selectablePlayers[0]?._id ?? ''
        } else {
            selectablePlayers = players
        }
    }

function addPlayerToTournament() {
        tournament.players = [...tournament.players, player_id];
        player_id = "";
        console.log(tournament.players);
        axios
            .put(
                "http://localhost:3001/api/tournaments/" + tournament_id,
                tournament
            )
            .then((response) => {
                getTournament();
            });
    }

</script>

<body>
      <div>
                <h3>Add Players</h3>
                <!-- Add an input element for the search bar -->
                <div
                    class="input-button-container mb-2"
                    style="display: flex; align-items: center;"
                >
                    <input
                        class="rounded line"
                        type="text"
                        bind:value={searchTerm}
                        placeholder=" Search for a player"
                    />
                    <button
                        class="btn btn-primary line"
                        on:click={addPlayerToTournament} disabled={player_id === ''}>Update</button
                    >
                </div>

                <select class="form-select" bind:value={player_id} id="player">
                    <option value="" disabled>please select player</option>
                    {#each selectablePlayers as player, i}
                        <option value={player._id}>{player.name}</option>
                    {/each}
                </select>
            </div>
</body>

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

Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers. I am struggling ...

Guide to making an object with a value sourced from the redux store

I am looking to develop an object with custom getters and a key representing language. Depending on the language key, different values should be returned by the getters. This is specifically for a customizable language selection feature. As an example, one ...

Contrast objects and incorporate elements that are different

In my scenario, I have a list of days where employees are scheduled to work. However, on the website, I need to display the remaining days as leave. In cases where an employee has two different shifts, there can be two elements in the object. var WorkDays ...

Tips for implementing a method to switch CSS properties of a main container by using a checkbox within its child element in a Svelte component

It took me a while to figure this out, but I still feel like my implementation is not ideal. I'm confused as to why things break when I remove the checkedActivities.has(activity) ? "checked" : "unchecked", because I thought TypeScr ...

When adding a new div, ensure it is counted and delete it once a new div is added

When clicked, a new div is added. When clicked again, another div with the same content is created as a duplicate. Q: Is there a way to remove the previous div when a new one is created? $(document).on('click', '.LibSectOpen', functio ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...

"Upload a text file and create a JavaScript variable that contains the text within it

I am currently developing a library and I need to add a feature that reads the contents of a text file. Currently, it only returns the path. How can I modify it to return the actual content of the file? function displayFileContent() { var file = do ...

Setting up the customized filename for precompiled Handlebars templates

When compiling Handlebars templates with the NPM package, is there a way to manually adjust the name/index that is generated? In my experience using Handlebars in various environments like Rails, NodeJS, and PHP, I've observed that the generated temp ...

What should be placed in the viewRef: MapViewNativeComponentType parameter when utilizing React Native Maps in the current.fitToSuppliedMarkers function?

useEffect(() => { if(!origin || !destination) return; mapRef.current.fitToSuppliedMarkers(["origin", "destination"], { edgePadding: { top: 50, right: 50, bottom: 50, left: 50} }) }, [origin, destination]); I'm currently in t ...

Issue with autoplay slideshow functionality not activating when opened in a new tab

The owl.carousel.js plugin is used for creating a jQuery slideshow. Initially, the slideshow works correctly, but I noticed that the autoplay feature stops working when I open a new tab in Firefox or Chrome. Demo : Demo : $(document).ready(function () ...

Using React and Redux to update the state of an object with the current state

Upon mounting my component, I make a call to an API and upon success, the state is updated with the following data: { "brief":"No brief given", "tasks":[ { "_id":"5c74ffc257a059094cf8f3c2", " ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

Modifying properties within child components

Within my parent Vue Page, I have inserted a FormInput component inside my form. new.vue <b-form @submit.prevent="submit"> <FormInput :name="name"/> <b-button @click="submit">Save</b-button> <b-form> <script> i ...

I attempted to implement dialog functionality using material-ui code from the documentation, but for some reason it's not functioning correctly. Can anyone point out what I might

I tried implementing a material-ui dialog feature for React, but I'm facing issues with it. When clicking on the contact button, the handleClickOpen method is not being triggered at all. The contact button is supposed to open the dialog box, and all ...

Troubleshooting the Height Problem in Material-UI's Menu

I am trying to make the menu height responsive by setting it equal to the window height using CSS. I want the menu height to increase as the page length increases due to added elements. I have attempted using "height:100%" and "height: 100vh" in the styles ...

I must create a dropdown and lift up feature similar to the one provided in the example

I am looking to implement a drop-down navigation bar on the top right and a pop-up button/links on the top left. The drop-down menu should appear when the screen size reaches a certain pixel width. If you can't see the drop-down navigation (NAV), adju ...

Does the onChange event fire when the value is modified by the parent element?

let [number, set_number] = useState({x: 1}); <ChildComponent number={number} onUpdate={onUpdateFunction} </ChildComponent> set_number({x: 2}) After running set_number({x: 2}), will this action prompt the execution of onUpdateFunction refere ...

transferring JSON information to a template in a NodeJs application

Currently, I am performing some filtering on my JSON data and storing the result in a variable called driver. The driver variable contains JSON data that I want to pass unchanged to the view. My main query is: How can I effectively send the data stored i ...

The position of the jQuery VirtualKeyboard is not displaying correctly

I'm currently experiencing an issue with the placement of the keyboard while using the Mottie/Keyboard plugin. The images provided below illustrate my desired outcome and the current behavior: https://i.sstatic.net/GULve.png Despite my attempts, the ...

Tips for leveraging Backbone.js for creating dynamic single page websites

I am eager to create my own personal website with a unique functionality similar to this example: The idea is to have the entire website contained within a single HTML page, where clicking on a navigation item will dynamically load only the necessary info ...