Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to submit a select menu without a button

Is it possible to auto submit a select menu when the selection changes without using a button to submit the form. I have four of these on my page and using a button for each uses up too much space. By Select Menu, I mean:

<select name="something" class="something" title="something something">
  <option selected="selected">Option One</option>
  <option >Option Two</option>
</select>

I would also like to add a confirm popup for the on change event. The following is what I use for buttons but it does not work for the select menu.

onclick="return confirm('do you haz teh codz?');"

Any link to articles tutorials or examples would be greatly appreciated!

Thanks


2 Answers

This is more appropriately tagged 'javascript' since it's javascript that you'll use to do it.

Add an 'onchange' event to the select. In the example below, 'form' should be substituted for your favourite method of targeting the form node.

<select name="something" class="something" title="something something" onchange="form.submit()">
<option selected="selected">Option One</option>
  <option >Option Two</option>
</select>
like image 179
mwotton Avatar answered Jan 31 '26 20:01

mwotton


You need a JavaScript solution, not a PHP solution. PHP can only handle form data after it's been sent to the server; i.e., when the form has been submitted.

You can use JavaScript to:

  1. Add an event listener to the <select> to trigger when it changes (onchange).
  2. When the <select> changes, get its current value.
  3. Based on the value, redirect the user (change window.location) to the page you want them to go to.

Edit: I re-read your question and if you are just looking to submit the form when the user changes the <select>, then mwotton's answer is probably the way to go. (Of course, move the JavaScript away from the HTML; it doesn't belong there.)

For your confirmation, you can do something like this:

document.getElementById('my-select').onchange = function(){
    return confirm('do you haz teh codz?');
});

(It's always a good idea to keep your JavaScript away from your HTML. So just give your <select> an ID like id="my-select" and you can access it from the JavaScript. You can also use a JavaScript library like jQuery to greatly ease your JavaScript programming.)

like image 33
Josh Leitzel Avatar answered Jan 31 '26 20:01

Josh Leitzel