JJd
JJd

Reputation: 33

php onchange onload select

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.

Upvotes: 1

Views: 8325

Answers (1)

user2156884
user2156884

Reputation:

<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 ?

Upvotes: 1

Related Questions