Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Submit form on dropdown change

Good morning!

I know that this topic has been covered on SO before but I couldn't find the full answer to my specific situation below so I apologize if I missed the answer elsewhere.

Scope:

What I am trying to achieve is a drop down list (either done with pure HTML or java script, HTML is preferred) that can load a php file. Inside that php file it should be able to access the selected drop down's value.

What I have tried:


Method 1:

I have used a method like this before:

<form action="test.php" method="post">
<select name="dropdown" id="dropdown">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
</select>
<input name="submitbutton" type="submit" value="submit" />
</form>

Then clicking on the submit button, the test.php page loads and I can get the value of the dropdown using $_POST("dropdown"). This method works perfectly fine! However I want to submit the form WITHOUT need of the button, simply using the drop down onchange event instead.


Method 2:

I also tried using:

<form>
<select name='dropdown' onchange='this.form.submit()'>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
</select>
<noscript><input type="submit" value="Submit"></noscript>
</form>

which will reload the page onchange but not the test.php page.. Changing "this.form.submit()" to test.php doesn't work.


I feel like I am close with both but not quite there. I hope what I am trying to achieve is explained well enough.

Thank you for any responses ahead of time!

like image 595
Eric F Avatar asked Mar 20 '14 15:03

Eric F


2 Answers

Add:

<form action="test.php" method="post">

To method2 and it should work fine.

like image 127
michal.hubczyk Avatar answered Sep 27 '22 22:09

michal.hubczyk


Give your form a name:

<form name="form1" action="test.php">

....then your onchange would be: document.form1.submit();

BTW, this has nothing to do with PHP, since it is 100% on the client.

like image 31
Diodeus - James MacFarlane Avatar answered Sep 27 '22 23:09

Diodeus - James MacFarlane