Search code examples
javascriptvelo

Drop down menu directing to same URL


I have created a drop down menu with multiple options to chose from. However what ever option I chose it directs me to the same URL. In this case the last written code. Could someone please tell me what I have missed in the code?

import wixLocation from 'wix-location';

$w.onReady(function () {
    $w("#dropdown1").onChange((event, $w) => {
        console.log(event.target.value); //iPhone X
        wixLocation.to("/iphonex");
    });
});
$w.onReady(function () {
    $w("#dropdown1").onChange((event, $w) => {
        console.log(event.target.value); //iPhone XS
        wixLocation.to("/iphonexs");
    });
});
$w.onReady(function () {
    $w("#dropdown1").onChange((event, $w) => {
        console.log(event.target.value); //iPhone XS MAX
        wixLocation.to("/iphonexsmax");
    });
});

Solution

  • You only need one event handler. You need to go to the value

    If you have more than one, the last one is executed

    import wixLocation from 'wix-location';
    
    $w.onReady(function () {
        $w("#dropdown1").onChange((event, $w) => {
            var page = event.target.value); //"iPhone X" OR "iPhone XS" etc
            if (page) wixLocation.to("/"+page.replace(/\s+/g,"").toLowerCase());
        });
    });
    

    If you instead set the VALUE of the options to iphonex, iphonexs etc, then you can just do

        $w("#dropdown1").onChange((event, $w) => {
            var page = event.target.value); // "iphonex" OR "iphonexs" etc
            if (page) wixLocation.to("/"+page)
        });