Select dropdown value from variable - php

I wanted to have a dropdown's selected value be determined by the results of the a query. But whatever I try, its selected value stays at the very first option.
I've browsed multiple questions with the same problem, but none solved my problem.
I've tried this:
<select name="Period">
<option value="Day" <?php if($PeriodTXT == "Day") echo "selected"?>>Day</option>
<option value="Week" <?php if($PeriodTXT == "Week") echo "selected"?>>Week</option>
<option value="Month" <?php if($PeriodTXT == "Month") echo "selected"?>>Month</option>
<option value="Year" <?php if($PeriodTXT == "Year") echo "selected"?>>Year</option>
</select>
And this:
<select name="Period">
<option <?php echo ($PeriodTXT == 'Day')?"selected":"" ?> >Day</option>
<option <?php echo ($PeriodTXT == 'Week')?"selected":"" ?> >Week</option>
<option <?php echo ($PeriodTXT == 'Month')?"selected":"" ?> >Month</option>
<option <?php echo ($PeriodTXT == 'Year')?"selected":"" ?> >Year</option>
</select>
But it won't work. Also when I use echo "$PeriodTXT"; it echos "Week" (exactly as written in the options of the dropdown), so it should've selected "Week" but it doesn't.
EDIT: $PeriodTXT is supposed to show the selected interval that came with a number count (example "3 Day" it would only keep the "Day" part)
$usersdata = array();
while($row = mysqli_fetch_array($result))
{
$usersdata = $row;
}
$PeriodTXT = preg_replace("/\d+/u", "", $usersdata[4]);

Your problem was extra whitespace around the text while you were removing count with regex, so hidden extra whitespace was yielding condition as false,
$PeriodTXT = '3 Week';
$PeriodTXT = preg_replace("/\d+/u", "", $usersdata[4]); //without trim()
var_dump($PeriodTXT); // outputs string ' Week' (length=5)
but when we trim it
$PeriodTXT = trim(preg_replace("/\d+/u", "", $usersdata[4])); //with trim()
var_dump($PeriodTXT); // outputs string 'Week' (length=4)
So use trim() to fix that, working eg,
<?php
$usersdata = array();
$usersdata[4] = '3 Week';
$PeriodTXT = trim(preg_replace("/\d+/u", "", $usersdata[4]));
?>
<select name="Period">
<option <?php echo ($PeriodTXT === 'Day')?"selected ='selected'":"" ?> >Day</option>
<option <?php echo ($PeriodTXT === 'Week')?"selected ='selected'":"" ?> >Week</option>
<option <?php echo ($PeriodTXT === 'Month')?"selected ='selected'":"" ?> >Month</option>
<option <?php echo ($PeriodTXT === 'Year')?"selected ='selected'":"" ?> >Year</option>
</select>
Also notice I have changed the HTML part from "selected":"" to "selected ='selected'":""

I understand you send a form using POST method, and after you send it, you would like to try display it with the selected option.
Please describe what is $PeriodTXT variable and how do you set it up.
Here is a solution to make it easy, hope it will help you.
$sent = $_POST['Period'];
$options = aray("Day", "Week", "Month", "Year");
echo '<form method="post" action="">
<select name="Period">';
foreach ($options as $v)
{
$selected = ($sent == $v) ? ' selected' : null;
echo '<option value="'.$v.'"'.$selected.'>'.$v.'</option>';
}
echo '</select>
<input type="submit" value="send">
</form>';
EDIT:
Code with "while" you have posted, seems to be wrong.
You are creating $userdata variable each time when while() goes. In fact it's not a real array, as you want it to be. It only works, when you select only one record from database (when mysql_num_rows($result) == 1). Otherwise it' wrong.
It should be done this way:
$usersdata = array();
while($row = mysqli_fetch_array($result))
{
$usersdata[] = $row;
}
$PeriodTXT = preg_replace("/\d+/u", "", $usersdata[$index][4]);
Notice, that you have to know which row ($index variable) you are doing changes in.
$usersdata becomes an Associative array.
Use var_dump() function to check what a variable contains itself. I hope it will get you closer to the solution. If you need more help, you have to post more code, because for now not everything is clear here.

Related

How to Select Month from Combobox with php?

I have a combobox and It consists of the Month. the following code :
<select name='Bmonth' id='Bmonth'>
<option value='1'>January</option>
<option value='2'>February </option>
<option value='3'>March</option>
<option value='4'>April</option>
<option value='5'>May</option>
<option value='6'>June</option>
<option value='7'>July</option>
<option value='8'>August</option>
<option value='9'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
I want the page number is 4 received, Combobox to view 'April'. for example , if the address of page http//test.php?page=4,combobox view April ... No change in the combobox code!
You are passing a GET Parameter, so do:
<?php
//checking if GET URL exists, if yes store it in variable
$page = (isset($_GET['page']))?$_GET['page']:'';
?>
<!-- checking if variable value is 4, if yes, select the option -->
<option value='4' <?php echo ($page==4)?'selected':''?> >April</option>
and so on for all the options.
You could do this through javascript too, but since you haven't place javascript tag in your question, I'm not explaining that.
Define an array of months. Receive the month number via $_GET and store it in a variable. Get the corresponding month name from the array. Loop through the month array, and on each iteration, check if the month selected by the user is same as the current month ($name). If so, set $selected equal to selected='selected'. If not, set it to an empty string. Print the <option> tag.
<select name='Bmonth' id='Bmonth'>
<?php
$months = array(
1=>'January','February','March','April',
'May','June','July ','August','September',
'October','November','December',
);
$key = $_GET['page']; // Month number
$default = $months[$key]; // Month name
foreach ($months as $num => $name) {
$selected = ($name == $default) ? "selected='selected'" : "";
printf('<option value="%s" %s>%s</option>', $num, $selected, $name);
}
?>
</select>
Selecting a particular option in SELECT TAG works like this -
<SELECT>
<OPTION>Something
<OPTION SELECTED>Something Else // This option gets selected
In your case, you can assign the attr selected using prop() of jquery
<?php
$page = isset($_GET['page']) ? $_GET['page'] : "";
?>
$(document).ready(function(){
$("select").val("<?php echo $pg ?>").prop('selected', 'true');
});

load select box with a selected option using php

Hi I have come across a problem now I do have a solution however it involves many of if statements and I would like to know it there is a neater option
what I would like is
<select>
<option value ="00:00">00:00</option>
<option value ="01:00">01:00</option>
<option value ="02:00">02:00</option>
<option value ="03:00">03:00</option>
</select>
then get an value from and have that box selected
what I'm am currently thinking is
$selectedbox = array();
if($tablevalue == "00:00"){
$selectedbox[0] = 'selected="selected"';
}
if($tablevalue == "01:00"){
$selectedbox[1] = 'selected="selected"';
}
then have
<select>
<option value ="00:00" <?php echo $selectedbox[0]; ?>>00:00</option>
<option value ="01:00" <?php echo $selectedbox[1]; ?>>01:00</option>
<option value ="02:00" <?php echo $selectedbox[2]; ?>>02:00</option>
<option value ="03:00" <?php echo $selectedbox[3]; ?>>03:00</option>
</select>
is there an easier way of getting the same result
for ($i = 0; $i <= 3; $i++) {
$sel = ("0{$i}:00" == $tablevalue) ? ' selected="selected"' : '';
echo <<<EOL
<option value="0{$i}:00"{$sel}>0{$i}:00</option>
EOL;
}
I would get rid of the if statements and put the code inline with the option tag with a ternary. Ex:
<select>
<option value ="00:00" <?=$tablevalue=="00:00"?'selected="selected"':''?>>00:00</option>
<option value ="01:00" <?=$tablevalue=="01:00"?'selected="selected"':''?>>01:00</option>
<option value ="02:00" <?=$tablevalue=="02:00"?'selected="selected"':''?>>02:00</option>
<option value ="03:00" <?=$tablevalue=="03:00"?'selected="selected"':''?>>03:00</option>
</select>
Take a look at PHP switch statements: http://php.net/manual/en/control-structures.switch.php
I think you would want something like this:
switch ($tablevalue) {
case "00:00":
$selectedbox[0] = 'selected="selected"';
break;
case "01:00":
$selectedbox[0] = 'selected="selected"';
break;
//etc, etc
}
PHP switch is a better way to handle if statements if you're always comparing the same variable.

Set <select> tag selected value in PHP

What would be the best way to set tag selected value?
<select id="attr_field_10" name="config_eph_payment_type">
<option value="5">First</option>
<option value="1">Second</option>
<option value="2">Third</option>
<option value="3">Fourth</option>
<option value="4">Fifth</option>
<option value="7">Sixth</option>
</select>
The value comes from $config_eph_payment_type variable (5, 1, 2, 3, 4 or 7).
Something like this should work:
$options = array(
5 => "First",
1 => "Second",
...
7 => "Sixth"
);
echo "<select id=\"attr_field_10\" name=\"config_eph_payment_type\">";
foreach ($options as $k => $v) {
echo "<option value=\"$k\"";
if ($k == $config_eph_payment_type)
echo " selected";
echo ">$v</option>";
}
echo "</select>";
What we basically do is to store the options into an associative array. Then, we loop through it and keep checking if the value is equal to the variable $config_eph_payment_type.
<option value="5"<?php if ($config_eph_payment_type == 5) print ' selected="selected"'; ?>>First</option>
This is the easiest way to do it. You could also put the if at the beginning of the file and then define a variable, this would make the HTML code more readable
<?php
//at beginning
if ($config_eph_payment_type==5)
$fiveSelected = ' selected="selected"';
else
$fiveSelected = '';
?>
in your code
First

Getting variables in jquery mobile via PHP

I have an issue getting variables using PHP in a tablet site I have been working on. I have a search form on the homepage that passes variables to a list page. I then have the same search form in a 'refine search' dialog box which should pre-select the appropriate values depending on what has been passed, using PHP.
The problem is I can't seem to get the variables that have been passed (using PHP). For example I have this field in my search:
<select name="propertyType" id="propertyType">
<option value="">Any Type</option>
<option value="1"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="1") { echo ' selected'; } ?>>Houses</option>
<option value="2"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="2") { echo ' selected'; } ?>>Flats/Apartments</option>
<option value="3"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="3") { echo ' selected'; } ?>>Bungalows</option>
<option value="4"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="4") { echo ' selected'; } ?>>Other</option>
</select>
But when I pass any of these values my code does not pick them up and echo the relevant 'selected'.
The tablet site can be found here: http://muskermcintyre.co.uk/tablet Any help would be much appreciated!
Thanks.
I suggest you following syntax:
<?php
$values = array(
0 => 'Any Type',
1 => 'Houses',
2 => 'Flats/Apartments',
3 => 'Bungalows',
4 => 'Other'
);
$current = (int) $_GET['propertyType'];
?>
<select name="propertyType" id="propertyType">
<?php
foreach ( $values as $key => $value ) {
$selected = $key == $current ? 'selected="selected"' : '';
echo "<option value='$key' $selected >$value</option>";
}
?>
</select>
I've had a similar problem in the past and got round it by getting the query string using Javascript/jQuery.
A quick search gave me this which might help you if you go down a similar route:
How can I get query string values in JavaScript?

How can I add text into a certain area?

If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?

Categories