Home:ALL Converter>Not able to set the selected index in html using javascript

Not able to set the selected index in html using javascript

Ask Time:2020-08-13T23:49:42         Author:VATSAL JAIN

Json Formatter

This is my Javascript:

    var productId=this.dataset.product
    var action=this.dataset.action
    var a = document.getElementById(productId);
    var size = a.options[a.selectedIndex].value;
    var l = toString(document.getElementById(productId).selectedIndex);
    updateUserOrder(productId, action, size)

In this I am able to get the productId , action , a , size , l correctly but I am not able to set the index selected thereafter. When a user on my site clicks on add button the product is added to cart with the correct size and all and also the page refreshes . But as tried in my code the selected option does not change as I want it to and remains the default (index=0).

This is my html for reference:

<select class="selection-2 border" data-product={{product.id}}
               style="border: cadetblue;" name="size" id="{{product.id}}">
                <option value="S" id="S">S</option>
                <option value="M" id="M">M</option>
                <option value="L" id="L">L</option>

My problem summed up is that for example a user chooses an option which is at second index then after the page refreshes(as my code executes) the select box should show default option as the option with second index which is currently not happening.

Author:VATSAL JAIN,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/63398733/not-able-to-set-the-selected-index-in-html-using-javascript