ricky spires Posted December 14, 2012 Share Posted December 14, 2012 (edited) how do i get and echo the selected <select> in a form ? hello. i have a select drop down and i would like it so that when i select an item it with echo the name and also get the id so i can edit/delete if i want. at the moment when i press the submit it echos the name but i cant get the id in a $val to put in to my edit/delete url. also after i press the button the value in the drop does not stay the same. this is the code. <table class="properties" width="550" border="0" cellspacing="0" cellpadding="0"> <tr><td > <form name="submitPropType" method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <?php $propType = Prop_Types::find_all(); echo "<select id='propType' name='propType'>"; foreach($propType as $pType) { echo "<option name='$pType->name'>$pType->id - $pType->name</option>"; } echo "</select>"; ?> <input type="submit" name="submitPropType" value="Select" /> <?php if($_GET){ echo 'You selected:'.$_GET['propType']; } ?> </form> </td> <td><a href="edit_prop_type.php?id='.$pType->id.'">Edit</a></td> <td><a href="delete_prop_type.php?id='.$pType->id.'">Delete</a></td> </tr> </table> .ps. maybe i could do it without the submit button using javascript ? thanks rick Edited December 14, 2012 by ricky spires Quote Link to comment https://forums.phpfreaks.com/topic/271993-how-do-i-get-and-echo-the-selected-in-a-form/ Share on other sites More sharing options...
DavidAM Posted December 14, 2012 Share Posted December 14, 2012 Typically, you would put the ID in the value attribute of the OPTION tag. Then the form sends the ID of the selected entry. If you want to display the name, you would look it up using the (unique) ID. To solve the change on submit, that's a new page load, you have to add the "SELECTED" attribute to the OPTION tag that was selected last time around. $idSelectedByUser = (isset($_GET['propType']) ? $_GET['propType'] : ''); echo "<select id='propType' name='propType'>"; foreach($propType as $pType) { echo "<option name='" . $pType->name . "' value='" . $pType->id . "'" . ($pType->id == $idSelectedByUser ? " SELECTED='SELECTED' " : "") . ">" . $pType->id . " - " . $pType->name . "</option>"; } echo "</select>"; Quote Link to comment https://forums.phpfreaks.com/topic/271993-how-do-i-get-and-echo-the-selected-in-a-form/#findComment-1399370 Share on other sites More sharing options...
ricky spires Posted December 14, 2012 Author Share Posted December 14, 2012 Thats great. thanks. gave me a good place to work from Quote Link to comment https://forums.phpfreaks.com/topic/271993-how-do-i-get-and-echo-the-selected-in-a-form/#findComment-1399374 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.