1

If I have an html form and select statement like,

<form method="post">
<select name="sortOrder" onchange="form.submit()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select></form>

and then a php switch statement which runs some stuff depending on the selection,

switch($_POST['sortOrder']){
case '1':
//execute this
break;
case '2':
//execute this
break;
case '3':
//execute this
break;

I want option 1 to load by default when the page loads. Unfortunately when the page loads it doesn't display anything until I select an option and then it always defaults to option 1 so I can't ever execute an onchange select to option 1 either. I tried incorporating the use of onload and onchange simultaneously but I think that's probably a poor way to do it, and it didn't work for me. I have been searching but can't find an answer specific to mine.

2
  • 1
    write the code in case 1 where your displaying the form. Commented Mar 12, 2013 at 11:32
  • 1
    The best way would be to create a blank option so then you always have to select either 1,2 or 3. I don't think it's good practice to default to '1' without including a submit button. Commented Mar 12, 2013 at 11:33

1 Answer 1

1
<form method="post">
<select name="sortOrder" onchange="form.submit()">
<option value="0">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select></form>

Php:

if(!isset($_POST['sortOrder']) {
 $sortOrder = 1;
} else {
 $sortOrder = $_POST['sortOrder'];
}
switch($sortOrder){
case '1':
//execute this
break;
case '2':
//execute this
break;
case '3':
//execute this
break;

So you tell PHP that the default is 1 if something selected use that select number so you don't need to use option value 0;

You want to load another page when you load this page? Or you wanne put somestuff from 1 afther this from ?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.