javascript - 从选择元素中获取超过选项标签的值
问题描述
在我的反应应用程序中,我有一个select
标签来选择一些选项。这些选项从 API 中获取并映射如下所示。
<select
id="numberbase__select"
onChange={this.onSelectExistingNumberBase}>
<option selected disabled hidden>Select a number base</option>
{this.props.tenantNumberBases.NumberBases.map((value, index) => {
return (
<option value={value.uuid}>{value.numberBaseName}</option>
);
})}
</select>
为了改变这个值,我使用了下面的辅助方法。
onSelectExistingNumberBase = (e) => {
this.setState({
existingNumberBase: e.target.value
});
}
这样我就可以获得uuid
映射数组值的 。但除了uuid
,我也想得到numberBaseName
。我尝试使用e.target.id
. 但它没有用。我之所以能够得到uuid
,是因为我已将其添加为option
标签的值。我怎样才能得到更多的价值uuid
呢?请帮忙。
解决方案
There might be few ways to achieve this. But I'll post here the solution that helped me.
First in select option, code like this.
<select
onChange={this.onSelectExistingNumberBase}>
<option selected disabled hidden>Select a number base</option>
{this.props.tenantNumberBases.NumberBases.map((value, index) => {
return (
<option value={value.uuid} id={value.numberBaseName}>{value.numberBaseName}</option>
);
})}
</select>
Then in the onChange helper method I followed something like following.
onSelectExistingNumberBase = (e) => {
this.setState({
existingNumberBase: e.target.value,
numberBaseName: e.target.options[e.target.selectedIndex].text,
});
}
I was able to get options and then the value inside the option tag using selected index. I hope this will help someone who has the same problem.
推荐阅读
- python - 在 pydantic 模型中包含非验证方法是不好的做法吗?
- python - 尝试将数据插入 sql-alchemy 数据库(烧瓶)时出错
- react-native - React Native,Drawer 导航图标被剪掉
- c# - 错误:在项目输出中找不到指定的 EntryPointExe 'MyApp.UWP.exe'
- c++ - 如何在 ECS 模型中组织实体?
- php - 如何使用 php 组合 JSON 对象?
- mysql - 获取两个连接表的总和,其中两个表中可能存在唯一数据
- python - 重复使用 GradientTape 进行多次雅可比计算
- apache-kafka - 当分区的领导者与其他生产者分离时会发生什么?
- pdf - 未找到“外部参照”关键字或外部参照表格式错误