onchange event in magento 2

onchange event in magento 2

September 6, 2026 · Illustrated author avatarBy Stefan Bogdanescu
onchange event in magento 2

Onchange Event Handling for Magento 2 Area Drop-down

Hello fellow developers! Today, let’s dive into handling onchange events for a drop-down menu that filters another drop-down or list in Magento 2. We’ll be using the Magento\Theme module as our base to create a custom block and controller.

The Problem at Hand

Our developer here is trying to implement an onchange event for a city drop-down, where changing the selected city should update the associated area options without refreshing the entire page. They have created the necessary block and collection methods but are struggling with the implementation of the AJAX call in their controller.

Understanding the Current Setup

First, let’s break down what we’re working with:

  1. A custom block Vac\Block\Vac that retrieves area data based on the selected city using a collection filter.
  2. An onchange event listener for the city drop-down element (<select id="city">).
  3. An AJAX post request to a URL pointing to their controller.

Step 1: Create a Custom Controller

To handle the AJAX request, we need to create a new controller within our custom module. Let’s assume you have already created Vac as your vendor name and Magento2 as your module name.

Create a file at Vendor/Magento2/Controller/Area/Index.php:

namespace Vendor\Magento2\Controller\Area;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;

class Index implements HttpPostActionInterface
{
    private $areaRepository;

    public function __construct(
        \Vendor\Magento2\Model\AreaRepository $areaRepository
    ) {
        $this->areaRepository = $areaRepository;
    }

    public function execute()
    {
        $cityId = (int) $this->getRequest()->getParam('city_id');

        if ($cityId > 0) {
            $areas = $this->areaRepository->findByCityId($cityId);
            $html = '<option value="">Select Area</option>';
            foreach ($areas as $area) {
                $html .= '<option value="' . $area->getAreaId() . '">' . $area->getArea() . '</option>';
            }

            return $this->resultFactory->create(ResultFactory::TYPE_RAW)->setContents($html);
        } else {
            // Handle error scenario
            return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData(['error' => 'Invalid city ID']);
        }
    }
}

This controller accepts a city_id parameter, finds the associated areas using the repository, and generates an HTML string for the area options. It then returns this string as a raw content.

Step 2: Update the AJAX URL

Now that we have our controller ready, let’s update the AJAX request in your script:

jQuery('#city').on('change', function () {
    jQuery.ajax({
        url: "<?php echo $this->getUrl('magento2/area/index')?>",
        data: {city_id: jQuery("#city").val()},
        type: "POST",
        success: function(data) {
            jQuery('#area').html(data);
        }
    });
});

We’ve replaced the URL with a call to getUrl, which generates the correct URL for our new controller.

Step 3: Ensure the Repository Method

To make sure the repository method works as expected, your AreaRepository should have a public method named findByCityId:

public function findByCityId($cityId)
{
    $collection = $this->getCollection()->addFieldToFilter('city_id', $cityId);
    return $collection;
}

Conclusion

With these steps, you should now be able to successfully implement the onchange event for your city drop-down. Changing the selected city will trigger an AJAX request to your Index.php controller, which will generate and update the associated area options in real-time without a full page reload.

Remember to always ensure that your code follows best practices for security, performance, and maintainability. If you need further assistance or want to explore more advanced features like UI components in Magento 2, feel free to check out our blog at Laravel Company.

Happy coding!

Magento 2 Indexing Extensions Themes

Our network