Mark elements in a selectbox from parameter in URL - php

I have a little problem with a selectbox that have to have some marked options from a URL parameter.
I have an URL that can look like this
index.php?page=edit&lid=4&recs=1,4,7&hl=Test&lhash=7c2cd87dad07ac99a00e92041a5d6a38
Where I want to use 1,4,7 from the recs parameter to mark the mailgroups with ID 1, 4 and 7 in my selectbox like
<select name="groups" multiple="multiple">
<option value="1" selected="selected">Group 1</option>
<option value="2">Group 2</option>
<option value="3">Group 3</option>
<option value="4" selected="selected">Group 4</option>
<option value="5">Group 5</option>
<option value="6">Group 6</option>
<option value="7" selected="selected">Group 7</option>
<option value="8">Group 8</option>
</select>
I tried to use this to make a variable with the selected="selected" value
$recis = explode(",", $_GET["recs"]);
foreach($recis as $rec) {
if($row["mailgroup_id"] == $rec) {
$sel = 'selected="selected"';
} else {
$sel = '';
}
}
And then
<option value="'. $row["mailgroup_id"] .'" '. $sel .'>'. $row["mailgroup_name"] .' - '. $row["country"] .'</option>
But that doesn't seem to work as all groups become marked

why don't you try loop on mailgroup_id record set
$recis = explode(",", $_GET["recs"]);
while($row=mysql_fetch_array($rs))
{
if( in_array($row["mailgroup_id"], $recis))
{
$sel = 'selected="selected"';
}
else
{
$sel = '';
}
// Option Code
}
Option Code
<option value="'. $row["mailgroup_id"] .'" '. $sel .'>'. $row["mailgroup_name"] .' - '. $row["country"] .'</option>

IT seems to me that the value of $sel just keeps changing throughout the loop, but then when you print it is just whatever it was set in the last loop iteration. What you need is this
foreach($recis as $rec) {
if($row["mailgroup_id"] == $rec) {
$sel = 'selected="selected"';
} else {
$sel = '';
}
// print the option tag here or store the $sel value
// for the given mailgroup_id
}
p.s. why call it $sel instead of $selected? "sel" can mean many things, don't be afraid of longer names - it improves readbility

Try this:
$recis = explode(",", $_GET["recs"]);
foreach($recis as $rec) {
if($row["mailgroup_id"] == $rec) {
$row["selected"] = 'selected="selected"';
} else {
$row["selected"] = '';
}
}
And in the html you can do this:
<option value="'. $row["mailgroup_id"] .'" '. $row['selected'].'>'. $row["mailgroup_name"] .' - '. $row["country"] .'</option>

Related

How to have a value already selected from <select> tag

I have the following dropdown implemented:
<select style="margin-left:25px;">
<option value="null"> </option>
<option value="single">Single</option>
<option value="in_a_relationship">In a relationship</option>
<option value="engaged">Engaged</option>
<option value="married">Married</option>
<option value="open_rel">In an open relationship</option>
<option value="divorced">Divorced</option>
</select>
Say for example, a user has already selected Single from the drop down menu. When they do back to this page, I want single to be already chosen from the list. For text fields I can simply get the value from the database and then assign it to a variable and then echo it in the value. I.e.
$get_data2 = mysqli_query ($connect, "SELECT * FROM user_bio WHERE username = '$username'");
$row3 = mysqli_fetch_assoc ($get_data2);
$bio = $row3['about_me'];
and then do ...
<textarea name="biotextarea" form="change_details" rows="4" cols="60" maxlength="255"><?php echo $bio; ?> </textarea>
How can I do this for a select tag?
Here's how to select the option Single in HTML :
<select style="margin-left:25px;">
<option value="null"> </option>
<option value="single" selected>Single</option>
<option value="in_a_relationship">In a relationship</option>
<option value="engaged">Engaged</option>
<option value="married">Married</option>
<option value="open_rel">In an open relationship</option>
<option value="divorced">Divorced</option>
</select>
So, how to set this in PHP?!
Well, you could generate your <select> element like this :
<?php
$options = [
'null' => ' ',
'single' => Single',
'in_a_relationship' => 'In a relationship',
'engaged' => 'Engaged',
'married' => 'Married',
'open_rel' => 'In an open relationship',
'divorced' => 'Divorced'
];
?>
<select style="margin-left:25px;"><?php
foreach($options as $key => $value) {
echo '<option value="' . $key . '"';
if ($key === $row3['status']){
echo ' selected';
}
echo '>' . $value . '</option>';
}
?></select>
Setting a preselected option on a select tag requires you to put a selected attribute on the selected option.
<select style="margin-left:25px;">
<?php
$options = array(array("null"," "),array("single","Single"),array("in_a_relationship","In a relationship"),array("engaged","Engaged"),array("married","Married"),array("open_rel","In an open relationship"),array("divorced","Divorced"));
foreach ($option in $options){
if ($option[0] == $row3['status']){
$selected = 'selected ';
}
else{
$selected = '';
}
echo '<option '.$selected.'value="'.htmlspecialchars($option[0]).'">'.htmlspecialchars($option[1]).'</option>';
}
?>
</select>
The solution of Musa it's OK, but If you don't want to change your PHP too much
you can do the task with Javascript.
With jQuery or pure Javascript
function selector(id, value){
select = document.getElementById(id);
for(i=0;i<select.options.length;i++){
if(select.options[i].value == value){
select.selectedIndex = i;
}
}
}
//Pure Javascript
selector("status", "engaged")
//With jQuery
jQuery('#status').val('married');
Check this Snippet

How to make dropdown option selected against a variable in php

I have a dropdown like the following.
<select>
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
I am getting a value from data base in $selected_value variable. Based on this value I want to make one option from the above select to be selected.
Eg: If $selected_value = Mr, <option value="Mr" selected>Mr</option>
if $selected_value = Dr, <option value="Dr" selected>Dr</option>
update:
now when i am inspecting element i am getting like below.but not selecting Dr.but it is orking in w3schools try editor.
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected="selected">Dr</option>
<option value="Prof">Prof</option>
</select>
update 2
see screen shot:
update3
now it works! added name for <select>
This will work for you problem
try this code
<select>
<option value="Mr" <?=($selected_value=="Mr") ? "selected" : ""?>>Mr</option>
<option value="Dr" <?=($selected_value=="Dr") ? "selected" : ""?>>Dr</option>
</select>
try this..
<option value="Mr" <?php if($selected_value == 'Mr') echo 'selected' ?>>Mr</option>
<option value="Dr" <?php if($selected_value == 'Dr') echo 'selected' ?>>Dr</option>
<option value="Prof" <?php if($selected_value == 'Prof') echo 'selected' ?>>Prof</option>
Or you can use by using jquery
<script>
$('select option[value="<?php echo $selected_value ?>"]').attr('selected','true')
</script>
As per your current HTML use the code below:
<select name="your_select_name">
<option <?php echo (($selected_value=="Mr")?"selected":"") ?> value="Mr">Mr</option>
<option <?php echo (($selected_value=="Dr")?"selected":"") ?> value="Mr">Dr</option>
<option <?php echo (($selected_value=="Prof")?"selected":"") ?> value="Mr">Prof</option>
</select>
If the value of this variable($selected_value) returns "Dr" then 2nd option will be selected. And also give a name of your select tag.
I changed my solution so it fits yours I hope.
UPDATE:
<select name="dropdownlist">
<?
$options = array("Mr", "Dr", "Prof");
foreach($options as $option){
if($_POST['dropdownlist'] == $option){
echo '<option selected="selected">' .$option. '</option>';
}else{
echo '<option>' .$option. '</option>';
}
}
?>
</select>
If you also have an array of your options you could create the option tags by looping through each one of them. In that loop you then can check if the $selected_value matches $option_value like so:
<select>
<?php foreach($options as $option_value => $option_displayName) : ?>
<option
value="<?php echo $option_value; ?>"
<?php echo $option_value == $selected_value ? 'selected' : ''; ?>>
<?php echo $option_displayName; ?>
</option>
<?php endforeach; ?>
</select>
To do what you want you'd have to build the select dynamically like the following example:
<?php
$selects = array(
array('name' => 'Mr', 'value' => 'Mr'),
array('name' => 'Dr', 'value' => 'Dr'),
array('name' => 'Prof', 'value' => 'Prof'),
);
$selected_option = 'Dr';
echo '<select>';
foreach($selects as $select) {
if($select['value'] == $selected_option) {
echo '<option value="'.$select['value'].'" selected>' .$select['name']. '</option>';
} else {
echo '<option value="'.$select['value'].'">' .$select['name']. '</option>';
}
}
echo '</select>';
?>
Which outputs:
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected>Dr</option>
<option value="Prof">Prof</option>
</select>
Example
Try as follows .
<select name="select_options">
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
After hit submit button. Then you will get value in $_POST['select_options']
There are many ways to achieve what you're doing. I can think of two straight ways to do this.
The first is ugly:
Insert in each option a php tag and check if value is selected:
<select>
<option <?php if ($selected_value == 'Mr') echo 'selected'; ?> value="Mr">Mr</option>
<option <?php if ($selected_value == 'Dr') echo 'selected'; ?> value="Dr">Dr</option>
<option <?php if ($selected_value == 'Prof') echo 'selected'; ?> value="Prof">Prof</option>
</select>
Otherwise, I would personally write a little helper
function generateSelect(array $entries, $selected)
{
$ret = '<select>'
foreach ($entries as $entry) {
$ret .= '<option';
if ($entry == $selected) {
$ret .= ' selected';
}
$ret .= ' value="'.$entry.'"';
$ret .= '>'.$entry.'</option'>;
}
return $ret;
}
It is just an example and its functionality could be expanded. It SHOULD work, but I haven't tried it myself (wrote it quickly)
You have mistaken syntax
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected="selected">Dr</option>
<option value="Prof">Prof</option>
</select>
this will work
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected>Dr</option>
<option value="Prof">Prof</option>
</select>

HTML selecting last selected dropdown value?

I'm dealing with a registration form at the moment, specifically, I'm dealing with redisplaying any information the user enters into the inputs if there is an error in the registration verification.
Normally, when a user hits 'submit' - if there is an error, the page refreshes and they are echoed out and the form is redisplayed. The problem is there is sometimes genuinely valid information in some of the fields, and by regrabbing that data, it can be redisplayed using the value attribute and the isset() function like so (if of course that data has been POSTed, which in this case it has):
<input type="email" name="anEmail"
value=" <?php echo (isset($email)) ? $email : false; ?>" />
That works fine for the <input> element, but is the same achievable with a dropdown list through the <select> element?
I initially tried:
<select name="region"
value="<?php echo (isset($region)) ? $region : 'Auckland'; ?>" >
<!-- with 'Auckland' being the default value of the list -->
However, it doesn't seem like that value="" is a valid attribute for the <select> tag.
Any ideas on how I could accomplish this? Cheers.
function build_select($name, array $options = NULL, $selected = NULL)
{
foreach($options as $value => $option)
$return .= ($value != $selected)? '<option value="'.$value.'">'.$option.'</option>': '<option selected="selected" value="'.$value.'">'.$option.'</option>';
return '<select name="'.$name.'">'.$return.'</select>';
}
echo build_select('region', array('Lorem' => 'Ipsum', 'Auckland' => 'Auckland', 'Ipsum' => 'Lorem'), 'Auckland');
HTML
<select name="region">
<option value="Lorem">Ipsum</option>
<option selected="selected" value="Auckland">Auckland</option>
<option value="Ipsum">Lorem</option>
</select>
You have to add selected="selected" to specific option. Like so:
<select name="region">
<option value="opt1">Option 1</option>
<option value="opt2" selected="selected">Option 2</option>
<option value="opt3">Option 3</option>
<option value="opt4">Option 4</option>
</select>
With this code Option 2 is selected
And in pehe you have to check if specific option equals the input.
<option value="opt4"<?php if ($region == "opt2"){ echo ' selected="selected"'; } ?>>Option 4</option>
it's selected="selected", i think. or just "selected".
a quick example of how you might implement that:
case "value0":
$selected0 = "selected";
break;
case "value1":
$selected1 = "selected";
break;
<option value="value0" <?php echo $selected0;?>></option>
<option value="value1" <?php echo $selected1;?>></option>
function __selected($ctrlName,$value)
{
if(isset($_REQUEST[$ctrlName]) && trim($_REQUEST[$ctrlName]) == trim($value))
return "selected='selected'";
else
return false;
}
use like
<select name="cmbCondition">
<option value="Excellent" <?php echo __selected('cmbCondition',"Excellent")?>>Excellent</option>
<option value="Good" <?php echo __selected('cmbCondition',"Good")?>>Good</option>
<option value="Poor" <?php echo __selected('cmbCondition',"Poor")?>>Poor</option>
</select>
One way you can do this if number of options are not much:
In every option put the code:
<select>
<option selected="<?php echo (isset($region) && $region=='Volvo') ? $region : ''; ?>">Volvo</option>
<option selected="<?php echo (isset($region) && $region=='Saab') ? $region : ''; ?>">Saab</option>
<option selected="<?php echo (isset($region) && $region=='Mercedes') ? $region : ''; ?>">Mercedes</option>
<option selected="<?php echo (isset($region) && $region=='Audi') ? $region : ''; ?>">Audi</option>
</select>
But if options are much in number javascript code is needed to be written..
if(isset($region))
{
echo '
<script>$("#id option").each(function()
{
if($(this).val()=='.$region.')
$(this).attr("selected", "selected");
});
</script>';
}
Dynamiclly creating options basod on array.
Usage should be pretty straightforward.
<?php
function rennder_options($options = array(), $selection = null) {
if (!is_array($options)) {
return false;
}
$result = "";
foreach($option as $option) {
$option_str = '<option value="'.$option['value'].'"';
if ($selection !== null && $option['value'] == $selection){
$option_str .= ' selected="selected"';
}
$option_str .= '>'.$option['name'].'</option>';
$result .= $option_str;
}
return result;
}
$options = array(
array( "value" => "opt1", "name" => "Option 1" )
array( "value" => "opt2", "name" => "Option 2" ),
array( "value" => "opt3", "name" => "Option 3" ),
);
?>
<select name="region">
<?php echo render_options($options, $_POST['region']); ?>
</select>

Specify a default selected item for HTML form drop-downs

Typically when you need to select an item by default, you do:
<select>
<option value="1"> Volvo </option>
<option value="2" selected="true"> Saab </option>
<option value="3"> Mercedes </option>
<option value="4"> Audi </option>
</select>
Is it possible to get something like this?
<select selectedValue="2">
<option value="1"> Volvo </option>
<option value="2"> Saab </option>
<option value="3"> Mercedes </option>
<option value="4"> Audi </option>
</select>
It works out easier in PHP since you only have to soft-code one value, instead of handling the selected attribute on any possible <option/>.
There is no attribute like that on the <select> element. Assuming your <option> output is in a loop, I don't see how it makes a huge difference:
$selected = "2";
foreach($values as $key => $val) {
echo "<option value=\"" . $key . "\"" . ($key == $selected ? " selected=\"selected\">" : ">") . $val . "</option>";
}
(my PHP is a little rusty, that may not be 100% correct)
No, but you can add your default value to your id like
<select id="default-value-2">
then in your options, you have
<option value="2" <?php echo is_this_the_default_value ? selected='true' : '' ?>
or something to that effect(forgive me i forgot my php syntax, but i hope you get the point).
Anyway, that is a dirty fix also, so i suggest just adding a method to check for the default selected tag and printing it selected="selected" when it is the default. You can just call it once if you loop through your select options
Put JavaScript after the declaration of the listbox and set the selected index there:
<script>
document.getElementById('listBoxId').selectedIndex=<?php echo $INDEX ?>;
</script>
Something like this.
You can do it like this:
$value = 1;
<select>
<?php if($value==1) echo "<option selected='true'> Volvo </option>";
else echo "<option> Volvo </option>"; ?>
<?php if($value==2) echo "<option selected='true'> Saab </option>";
else echo "<option> Saab </option>"; ?>
</select>
PHP:
<select>
<option value="1" <?php echo ($row['status']==1) ? 'selected' : '' ?>>Permitido</option>
<option value="2" <?php echo ($row['status']==2) ? 'selected' : '' ?>>Bloqueado</option>
</select>
I found myself googling this to see if there was a better way to do it.
The best and cleanest answer is from #roryf, however if you are not looping through your data I thought it would be a lot cleaner to wrap it up in a function:
function set_selected($desired_value, $new_value)
{
if($desired_value==$new_value)
{
echo ' selected="selected"';
}
}
Then you would use it like this:
<?php $selected_value = 2; ?>
<select>
<option value="1"<?php set_selected('1', $selected_value); ?>> Volvo </option>
<option value="2"<?php set_selected('2', $selected_value); ?>> Saab </option>
<option value="3"<?php set_selected('3', $selected_value); ?>> Mercedes </option>
<option value="4"<?php set_selected('4', $selected_value); ?>> Audi </option>
</select>
This would set Saab as selected :)
Preload $statusid from DB then -> (i have to escape ")
PHP:
$option_0 = '';
$option_11 = '';
$option_12 = '';
$option_13 = '';
$option_14 = '';
$option_15 = '';
$option_16 = '';
if ($statusid ==0 ){
$option_0 = 'selected=\"\"';
}elseif($statusid ==11 ){
$option_11 = 'selected=\"\"';
}elseif($statusid ==12 ){
$option_12 = 'selected=\"\"';
}elseif($statusid ==13 ){
$option_13 = 'selected=\"\"';
}elseif($statusid ==14 ){
$option_14 = 'selected=\"\"';
}elseif($statusid ==15 ){
$option_15 = 'selected=\"\"';
}elseif($statusid ==16 ){
$option_16 = 'selected=\"\"';
}
HTML:
."<select id=\"id\" name=\"name\" >"
." <option {$option_0} value=\"0\">...TEXT...</option>"
." <option {$option_11} value=\"11\">TEXT</option>"
." <option {$option_12} value=\"12\">TEXT</option>"
." <option {$option_13} value=\"13\">TEXT</option>"
." <option {$option_14} value=\"14\">TEXT</option>"
." <option {$option_15} value=\"15\">TEXT</option>"
." <option {$option_16} value=\"16\">TEXT</option>"
."</select><br /><br />"
work Perfect for me.

PHP + form select options

I have a select that looks like this, it is written in in HTML and is not rendered via any php,
<select name="position">
<option value="left">Left</option>
<option value="right">Right</option>
<option value="centre">Centre</option>
</select>
The value gets sent to database and later on gets returned from the database as a variable in the form of $v['position'], using this and my original form how can I make the option that matches the varibale the default selection?
You didn't specify when the form displayed again.
If immediately when user is submitted the form, you need to insert this snippet to every option:
<option value="left"<?php echo $v['position'] == 'left' ? ' selected' : ''; ?>>Left</option>
<option value="right"<?php echo $v['position'] == 'right' ? ' selected' : ''; ?>>Right</option>
<option value="centre"<?php echo $v['position'] == 'centre' ? ' selected' : ''; ?>>Centre</option>
OR:
You must iterate through variables via PHP :(
$html = '<select name="position">';
$opts = array('left', 'right', 'centre');
foreach($opts as $option)
{
$html .= '<option value="' . $option . '"';
$html .= $option == $v['position'] . ' selected' : '';
$html .= '>' . ucfirst($option) . '</option>';
}
$html .= '</select>';
print $html;
You can create the options in a loop and check whether the current element equals the value in $v['position'] and set the selected attribute accordingly.
<?php
$options = array('left'=>'Left', 'right'=>'Right', 'centre'=>'Centre');
?>
<select name="position">
<?php foreach($options as $value=>$text):?>
<option value="<?php echo $value ?>"
<?php echo ($v['position'] == $value) ? 'selected="selected"' : '' ?> >
<?php echo $text ?>
</option>
<?php endforeach; ?>
</select>
You can do it with DOM without having to touch your HTML. If this is your HTML:
$template = <<< TPL
<select name="position">
<option value="left">Left</option>
<option value="right">Right</option>
<option value="centre">Centre</option>
</select>
TPL;
And this is the value that was selected:
$value = 'right';
You can do
$dom = new DOMDocument;
$dom->loadXml($template);
$xPath = new DOMXPath($dom);
$node = $xPath->query(sprintf('//option[#value = "%s"]', $value));
if($node->item(0)) {
$node->item(0)->setAttribute('selected', 'selected');
}
echo $dom->saveXML($dom->documentElement);
And that will output:
<select name="position">
<option value="left">Left</option>
<option value="right" selected="selected">Right</option>
<option value="centre">Centre</option>
</select>
try this
<select name="position">
<option value="left" <?php echo $v['position']=='left'?'selected="selected"':'' ?> >Left</option>
<option value="right" <?php echo $v['position']=='right'?'selected="selected"':'' ?>>Right</option>
<option value="centre" <?php echo $v['position']=='centre'?'selected="selected"'?:'' >>Centre</option>
</select>
<select name="position">
<option value="left"<?php echo ($v['position'] == 'left') ? ' selected="selected" : ''; ?>>Left</option>
<option value="right"<?php echo ($v['position'] == 'right') ? ' selected="selected" : ''; ?>>Right</option>
<option value="centre"<?php echo ($v['position'] == 'centre') ? ' selected="selected" : ''; ?>>Centre</option>
</select>

Categories