'change input value depending on select option
I've two arrays and they are from the same length. One array is for the articles and the other ist for the prices. The first array is going to a select option element. By selecting an article, the price from the other array should be displayed in an input field. So if I choose the second article from the options, the second price from the price array should be loaded in the input field value.
<?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" />
I don't have any clue how to get the array index of the selected option element and select than the index from the price array.
Solution 1:[1]
Here are two versions
window.addEventListener('DOMContentLoaded', function() {
const art = document.getElementById("art");
const setPrice = function() {
var val = art.value;
document.getElementById("price").value=val?val.split("|")[1]:"";
};
art.addEventListener("change", setPrice);
setPrice(); // 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 version
$("#art").on("change",function() {
var val = this.value;
$("#price").val(val?val.split("|")[1]:"");
}).change(); // initialise
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
