itachi77 Posted July 30, 2010 Share Posted July 30, 2010 Hi, just wondering if there is a way to reload the page with the form submitted when a value in a list is changed but without pressing a submit button. I have something like this <form method='post' action =""><select name='add' onchange=<?php $_SERVER['PHP_SELF']> <option>Option 1</option> <option>Option 2</option></select></form> This doesn't seem to be doing anything, it doesn't reload when an item is selected from the list. The purpose of this is depending on what option a user selects a text box will be shown so i want to be able to reload the page without pressing submit and can then use the variables sent. Thanks Quote Link to comment Share on other sites More sharing options...
Alex Posted July 30, 2010 Share Posted July 30, 2010 onchange="this.form.submit();" Quote Link to comment Share on other sites More sharing options...
itachi77 Posted July 30, 2010 Author Share Posted July 30, 2010 that worked great, thanks Alex. Just a question, why did the php reload in my script not work? Also, i didn't know this was javascript, could you give a brief explanation as it's the first time i have seen it. One slight hiccup I am having now is that when the page reloads i can work with the variable etc but the menu list does not display the option that was selected as default, it displays the first option in the list. So if option 2 was selected in the list, the page reloads and shows option 1 as default. Thanks Quote Link to comment Share on other sites More sharing options...
Alex Posted July 30, 2010 Share Posted July 30, 2010 PHP, being a server-side language, has nothing to do with what happens after the page loads. PHP just does whatever you tell it to do, sends the output to the browser and then has nothing to do with it afterwards. This is why to get the effect you're looking for you need to use JavaScript, a client-side language. The JavaScript is fairly straightforward, it just submits the form that the select element belongs to. In order to have to option remain selected you will have to loop over all the options and determine which one was selected. For that option you define the attribute selected (selected="selected"). Something like this: <form method='post' action =""> <select name='add' onchange="this.form.submit();"> <?php $options = array('option 1', 'option 2'); foreach($options as $option) { echo '<option value="' . $option . '"'; if(isset($_POST['add']) && $_POST['add'] == $option) { echo ' selected="selected"'; } echo ">$option</option>\n"; } ?> </select> </form> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.