I am trying to get the selected value from the dropdown, but have no luck.
<select class="form-control" name="cars" onchange="getAvailableCars();">
<?php getCars() ?>
</select>
getCars() function retrieves all available cars from the database, and they show in the dropdown menu.
Here is function getCars()
function getCars(){
$link = new mysqli("localhost", "root", "", "cars");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT CarID, CarCode, CarName FROM cars a WHERE CarAvailable = 1");
echo '<option value="">Select </option>';
while($record=mysqli_fetch_array($sql)){
echo '<option value= "' .$record['CarID']. '">' . $record['CarCode'] ."-|-". $record['CarName'] .' </option><br/>';
}
}
Then I created JS function which will get selected Card ID from the select menu.
<script>
function getAvailableCars() {
var car = document.getElementById("cars");
var selectedCar= car.options[car.selectedIndex].value;
console.log(selectedCar);
/*
var arr = {artikal:selectedCar};
$.ajax({ url: 'available-cars.php?a=1',
data: arr,
type: 'post',
success: function(output) {
document.getElementById("cars").value = output;
}
});
*/
}
</script>
Console displays issue:
Uncaught TypeError: Cannot read properties of null (reading 'options')
Also, I have tried with Jquery, but I got in console undefined.
var cars = $("#cars:selected").val();
I was following link below, any other too but for some reasons, I cannot get the selected value:
get-selected-value-in-dropdown-list-using-javascript