首页 > 解决方案 > 根据选择选项更改输入值

问题描述

我有两个数组,它们的长度相同。一个数组用于文章,另一个数组用于价格。第一个数组将指向一个选择选项元素。通过选择一篇文章,另一个数组中的价格应显示在输入字段中。因此,如果我从选项中选择第二篇文章,则价格数组中的第二个价格应加载到输入字段值中。

<?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" />

我不知道如何获取所选选项元素的数组索引并选择价格数组中的索引。

标签: javascriptphpjqueryhtml

解决方案


像这样的东西?假设我已经正确理解了这个问题

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

推荐阅读