How to make the select first option in forms to be selected after refresh?

Discussion in 'Programming' started by OaldDesign, Apr 27, 2011.

  1. #1
    Hey, i have a form where i use select options i have few options like 1,2,3,4
    now if i change the option from 1 to 3 and then hit refresh it stay as 3 and not going back to 1 (that happen in firefox, on some other browsers you won't see the problem).
    Wanted to know if there is any way to make it go to the first option after refreshing?
    I mean if when i enter the page it is on 1 and then i chose 3 and refresh it will go back to 1 instead of stay as 0.
    I think this is something that can be done by javascript and would be great to know what the solution for this.
     
    OaldDesign, Apr 27, 2011 IP
  2. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try this
    
    <html>
    <head>
    <script type="text/javascript">
    	window.onload = function () {
    		document.getElementById('myselect').options[0].selected = 'selected';
    	}
    </script>
    </head>
    <body>
    <form>
    <select id='myselect'>
    	<option>Option 1</option>
    	<option>Option 2</option>
    	<option>Option 3</option>
    </select>
    </form>
    </body>
    </html>
    
    Code (markup):
     
    Cash Nebula, Apr 27, 2011 IP
  3. OaldDesign

    OaldDesign Active Member

    Messages:
    448
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Working great thanks but there is small problem with that it working only for one select if i make other selects with the div id its not working.
     
    Last edited: Apr 28, 2011
    OaldDesign, Apr 28, 2011 IP
  4. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yes, that only resets the select with the ID "myselect". This will reset every select:
    
    <html>
    <head>
    <script type="text/javascript">
    	window.onload = function () {
    		var selects = document.getElementsByTagName('select');
    		for (var i=0; i<selects.length; i++) {
    			selects[i].options[0].selected = 'selected';
    		}
    	}
    </script>
    </head>
    <body>
    <form>
    <select>
    	<option>Option 1</option>
    	<option>Option 2</option>
    	<option>Option 3</option>
    </select>
    <select>
    	<option>Option 1</option>
    	<option>Option 2</option>
    	<option>Option 3</option>
    </select>
    </form>
    </body>
    </html>
    
    Code (markup):
     
    Cash Nebula, Apr 28, 2011 IP
  5. OaldDesign

    OaldDesign Active Member

    Messages:
    448
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    60
    #5
    Working great thanks a lot for you help
     
    OaldDesign, Apr 30, 2011 IP