How to retrieve selected value from dropdown menu using JavaScript

I need help getting the selected option value from a dropdown list and using it in my JavaScript code.

Here’s my dropdown setup:

<select name="customer_id" style="width: 70%;" class="form-control" id="customer_id" onchange="handleSelection(this.value);">
    <option value="">-- Choose Customer ID --</option>
    <?php
        $customers = fetch_customer_data();
        foreach ($customers as $item => $data) {
    ?>
            <option value="<?php echo $data->customer_id;?>"><?php echo $data->customer_id;?></option>
    <?php
        }
    ?>
</select>

I want to use the selected dropdown value in this button link:

<div class="action-area">
     <a href="javascript:ProcessForm('<?php echo $user['username'];?>', '**[SELECTED_VALUE_HERE]**');" class="btn-primary" style="width:50px; height:45px;">ADD</a>
</div>

What’s the best way to capture the dropdown selection and insert it into the JavaScript function call?

You can also store the selected value in a global variable and grab it when needed. This works great when multiple buttons or functions need the same dropdown value.

var selectedCustomerId = '';

function handleSelection(value) {
    selectedCustomerId = value;
}

Then modify your button to use the stored value:

<a href="javascript:if(selectedCustomerId) ProcessForm('<?php echo $user['username'];?>', selectedCustomerId); else alert('Select customer first');" class="btn-primary" style="width:50px; height:45px;">ADD</a>

This keeps your existing structure but gives you access to the selected value anywhere in your script. The inline check stops ProcessForm from running with empty values. I’ve used this pattern tons of times in legacy apps where I couldn’t restructure the existing markup.

Don’t hardcode the selected value in your anchor tag. Instead, use a button and grab the dropdown value dynamically when it’s clicked:

ADD

Then add this JavaScript:

function executeProcess() {
var dropdown = document.getElementById(‘customer_id’);
var selectedValue = dropdown.value;

if (selectedValue === '') {
    alert('Please select a customer ID first');
    return;
}

ProcessForm('<?php echo $user['username'];?>', selectedValue);

}

This gives you better control and validation. I’ve used this pattern in my projects - it’s way more reliable than updating anchor href attributes on the fly. The validation prevents empty selections from breaking your ProcessForm function.

you can also update the href directly when the dropdown changes. just modify your handleSelection function:

function handleSelection(value) {
    var addBtn = document.querySelector('.action-area a');
    if(value) {
        addBtn.href = "javascript:ProcessForm('<?php echo $user['username'];?>', '" + value + "');";
    }
}

this keeps your existing anchor tag working and updates it whenever someone picks a different option.