Search code examples
javascriptselectonchange

How to use data-attr to create an anchor in selectbox


When choosing an option from a selectbox, i want to create an anchor. Below works fine:

<select class="form-select name" onchange="location = this.value;">
    <option value="Naam" selected>Naam</option>             
    <option class="" value="index.php?name=John">John</option>
    <option class="" value="index.php?name=Susan">Susan</option>
</select>

But i prefer to seperate the anchor from the value. So i thought something like this should also work but unfortunately:

<select class="form-select name" onchange="location = this.attr.data-anchor;">
    <option value="Naam" selected>Naam</option>             
    <option class="" data-anchor="index.php?name=John" value="John">John</option>
    <option class="" data-anchor="index.php?name=Susan" value="Susan">Susan</option>    

</select>

Is there a way i can use something like data-anchor and trigger on that value with select?


Solution

  • This should work:

    <select class="form-select name" onchange="location = (this.selectedOptions[0].dataset.anchor);">
        <option value="Naam" selected>Naam</option>             
        <option class="" data-anchor="index.php?name=John" value="John">John</option>
        <option class="" data-anchor="index.php?name=Susan" value="Susan">Susan</option>    
    
    </select>