简体   繁体   中英

Get selected value from dropdown list

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

I think your problem is your car variable is not called right.

var car = document.getElementById("cars");

but your form have class = "form-control" and name = "cars" and dont have any id

<select class="form-control" name="cars" onchange="getAvailableCars();">

You may change car into

var car = document.getElementsByClassName("form-control");
// or
var car = document.querySelector(".form-control");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM