下拉选择不工作与单一选项在苗条



我在我的Svelte应用程序中有一个下拉菜单,显示玩家列表。我希望能够在这个列表中搜索一个球员,并有下拉菜单只显示匹配搜索查询的球员。但是,当列表中只有一个匹配的玩家时,我无法从下拉菜单中选择(更新)该玩家;但是下拉菜单只显示一个玩家。我如何解决这个问题?

选择

<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>

搜索栏

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

Update按钮

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

更新函数addPlayertoTournament

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

我已经尝试使用include函数来检查玩家的名字是否包含在搜索词中,然后使用if语句只显示下拉菜单中满足此条件的玩家。

对于如何解决这个问题,我将非常感谢任何帮助或建议。

我想感谢@Corrl用户的所有帮助和努力,为我们提供了一个可行的解决方案。我现在可以继续我的项目了,我非常感谢他们的贡献。我附上了最后对我有效的解决方案,如果你有任何问题请告诉我。

代码块

<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>

最新更新