Leave the form option selected

0

With .php and javascript how could I leave selected the option that the user selected in a form, after giving the input button to process the fields?

You get the value you selected, but I do not know how to get to the option and setAttribute selected selected

    <select id="id_of_select">
            <option></option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

        <button id="btn">Show selected</button>

<script>

 function show_selected() {
            var selector = document.getElementById('selectedIMon1');
            var value = selector[selector.selectedIndex].value;
	var index = selector[selector.selectedIndex].index;
              
	alert(value);
  
        }

       document.getElementById('btn').addEventListener('click', show_selected);
	
        ;
</script> 

Greetings

    
asked by Wallx 14.10.2018 в 22:26
source

1 answer

1

I guess what you're looking for is to match the selected index in a select , in your case selectedIMon1 , with another, id_of_select . It's quite simple, you only use the same property that you used to get the index, check this simple example:

<select id="select1">
    <option></option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
</select>

<select id="select2">
    <option></option>
    <option>two</option>
    <option>three</option>
    <option>four</option>
</select>

<button id="btn">Show selected</button>

<script>

function show_selected() {
    var selector1 = document.getElementById('select1');
    var selector2 = document.getElementById('select2');          

    selector2.selectedIndex = selector1.selectedIndex;

}

document.getElementById('btn').addEventListener('click', show_selected);
</script>

As you see, I only match the .selectedIndex property of the selector to the index I want to leave, in this case the index of my first selector select1 .

    
answered by 14.10.2018 / 22:51
source