javascript - 根据选择选项更改输入值
问题描述
我有两个数组,它们的长度相同。一个数组用于文章,另一个数组用于价格。第一个数组将指向一个选择选项元素。通过选择一篇文章,另一个数组中的价格应显示在输入字段中。因此,如果我从选项中选择第二篇文章,则价格数组中的第二个价格应加载到输入字段值中。
<?php
foreach($article as $art){
$arr_artnr[] = $art["artnr"];
$arr_artname[] = $art["artname"];
$arr_price[] = $art["price"];
}
?>
<select name="art" id="art">
<?php
foreach($article as $art){
?>
<option value="<?php echo $art["artnr"];?>"><?php echo $art["artname"] ?></option>
<?php
}
?>
</select>
<input type="number" name="price" id="price" value="" disabled="disabled" />
我不知道如何获取所选选项元素的数组索引并选择价格数组中的索引。
解决方案
像这样的东西?假设我已经正确理解了这个问题
document.querySelector("#art").onchange=function() {
var val = this.options[this.selectedIndex].value;
document.querySelector("#price").value=val?val.split("|")[1]:"";
}
document.querySelector("#art").onchange(); // initialise
<select name="art" id="art">
<option value="">Please select</option>
<?php
foreach($article as $art){
?>
<option value="<?php echo $art["artnr"]."|". $art["price"];?>|"><?php echo $art["artname"] ?></option>
<?php } ?>
</select>
<input type="number" name="price" id="price" value="" readonly />
jQuery版本
$("#art").on("change",function() {
var val = this.options[this.selectedIndex].value;
$("#price").val(val?val.split("|")[1]:"");
}).change(); // initialise
推荐阅读
- google-sheets - COUNTIF 具有绝对列,Google 表格中的相对行
- java - 检索由 EMF 比较计算的 ADD Diff 中的“值匹配”
- powershell - 如何通过 Powershell 从 AD 组设置所有者属性(不由其管理)?
- javascript - 如何使用 jquery 从浏览器中的 Cookie 获取 sessionid?
- android - 使用 Glide 库:如何在头像右侧设置相机图标?
- android - 如何正确调用 newInstance 方法?
- arrays - discord.js 将 .json 值导入变量
- amazon-web-services - 在 AWS ECS 集群中将 Grafana 部署为 FARGATE 服务
- html - 如何在有角材料的中心对齐标志?
- python - 构建docker镜像时无法安装sklearn