Home > Software engineering >  Keep the value on dropdown list after submitting form
Keep the value on dropdown list after submitting form

Time:01-03

How do I display the selected option on drop down list after submitting form? It always displays the first option.

     <form id="myform" >
        <label for="selectoption">Birimler</label>
        <select id="SelectOption" name="SelectOption" onchange="$('#myform').submit();" value="a">
            <option>Seçiniz</option>
            <option id="aYo" value="Yonetim">Yönetim</option>
            <option id="aAr"  value="Arge">ARGE</option>
            <option id="aDe"  value="Depo">Depo/Sevkiyat</option>
            <option id="aIK"  value="IKID">İnsan Kaynakları/İdari İşler</option>        
        </select>
    </form>

CodePudding user response:

Try this:

  <script type="text/javascript">
    function getOption() {
        selectElement = document.querySelector('#selectoption');
        output = selectElement.value;
        document.querySelector('.output').textContent = output;
    }
    </script>

or try this:

selectElement.options[selectElement.selectedIndex].value

selectedIndex---It is used to set or get the index of the selected element in the collection.

length---It is read-only property that is used to get the number of elements in the collection.

CodePudding user response:

You can save the value in localStorage like:

localStorage.setItem('selectOption', $(#SelectOption).val());

then your browser will remember this value even after page reload (form send), then you can fill your form by getting the value

$(#SelectOption).val(localStorage.getItem('selectOption'))

CodePudding user response:

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

Clicking on a "Submit" button, prevent it from submitting a form Clicking on a link, prevent the link from following the URL Kindly check this link.

try this

$(document).ready(function(){

    $('#SelectOption').change(function (e) {

        console.log($( "#SelectOption" ).val())
        let SelectOptionValue = $( "#SelectOption" ).val()
        console.log("click",SelectOptionValue)

        // $('#myform').submit();

        $( "#SelectOption" ).val("Depo")
        console.log($( "#SelectOption" ).val())
        console.log("click")
        e.preventDefault();
    });

});
  • Related