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?
Related
I have this easy select in PHP as echo (using Chosen JS):
echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\"
data-placeholder=\"Country...\" multiple class=\"chosen-select\">
<option value=\"dontcare\">dontcare</option>";
foreach ($states as $state) {
echo "<option value=\"" . $state->stat .
"\" >" . $state->stat . "</option>";
}
echo "</select> </th></tr>";
after submitting from and refreshing page values are not as selected.
If i have select with only one choice this is working for me:
var my_val = '<?=$_POST['price']?>';
$("#cenan").val(my_val).trigger("chosen:updated");
but i dont know how to set it as selected in case of array. Can you help me and show me some code? I spent hours and hours without any result.
You are POSTing the form data to the same page and then refreshing it, right?
If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array.
Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. Much easier on the eye.
foreach ($states as $state) {
if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
echo "<option value='$state->stat' selected>$state->stat</option>";
} else {
echo "<option value='$state->stat'>$state->stat</option>";
}
}
Lets suppose you have HTML select like following :
<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
Here is the solution :
<?php
$arr = ['a','b']; // PHP Sample Array
?>
var js_json = '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']
// initialize
$("#firstselect").chosen();
// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});
//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");
An option value is taken from the database and included in a select box along with other options. How can I set the value taken from the database as selected?
The value from the database is set as $row['value'] and equals s. In HTML the options look like so...
<select name="select">
<option value='xxs'>Extra, Extra small</option>
<option value='xs'>Extra small</option>
<option value='s'>Small</option>
<option value='m'>Medium</option>
<option value='l'>Large</option>
<option value='xl'>Extra Large</option>
<option value='xxl'>Extra, Extra small</option>
</select>
What I want is the $row['value'] (Small) option to be displayed on page load... Is this possible?
The good news is, this is possible and in PHP is quite simple really. First we put all of our options and their respective values in an array like so:
<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');
Follow this by opening the select box and calling upon the options array in a foreach loop...
echo '<select>';
foreach($options as $view=>$value){
As you may have noticed the array contains fields that look like 'Large'=>'l' and the for each loop is calling upon the options as $view=>$value. $view represents the name field, in this case 'Large' and $value represents the value field 'l'. This is important if you expect the user to see different options in the select box than what the values are set at.
Next we create the variable $selected which is going to be used to determine if there is a match between $row['value'] and $value...
$selected=($row['value'] == $value)? "selected" : "";
This is the same as using an if and else statement to set the variable, but shorter. The first section after the variable is asking if $row['value'] is equal to $value, if it does then $selected="selected" else (:) $selected is set to blank.
Next we include the options. Because it is in the foreach loop, we only need one line to insert all of the options...
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
Remember the $selected variable in the last step? Each time the foreach loop goes through a section of the options array set at the beginning, it checks to see if $row['value'] equals $value. If it does then $selected will be set as selected and that particular option will be the one that is shown on page load. It continues through the rest of the array until all views and values have been scanned and returns their respective options.
Finally we close the foreach loop and the select box...
}
echo '</select>';
And there you have it, an automatic way to make a select box option set as selected. A similar pattern can be used for check-boxes, radio selectors, tabs and more.
The full code...
<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');
echo '<select>';
foreach($options as $view=>$value){
$selected=($row['value'] == $value)? "selected" : "";
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
}
echo '</select>';
Given this array, and this value to be the selected value...
$options = array(
'Extra, Extra small' => 'xxs',
'Extra small' => 'xs',
'Small' => 's',
'Medium' => 'm',
'Large' => 'l',
'Extra Large' => 'xl',
'Extra, Extra Large' => 'xxl'
);
$selected = 'm'; // $selected can be swapped for $row['value'] as in the OP
There are several ways to dynamically construct the option tags inside of a <select> and set the selected attribute on one of them.
First the one-liner inside a foreach loop:
echo "<select name=\"select\">";
foreach($options as $text=>$value){
echo "<option value=\"$value\"" , ($selected == $value ? " selected" : "") , ">$text</option>";
}
echo "</select>";
This code block uses a ternary conditional operator aka conditional operator aka shorthand if/else aka inline conditon. Go here for further reading and examples.
By using double quotes " you avoid having to toggle back and forth between literal strings and variables. *You will have to escape double quotes that are nested inside of the string by prepending \. *Variables can be wrapped in curly brackets to isolate their variable name from the surround text. *Single quotes will not echo the value of the variable.) For continued read about quoting: reference
By using , (commas) instead of . (dots) to concatenate the string, performance is increased. one benchmark
By only adding a space before the selected attribute in the true condition (versus adding the space outside the condition on every iteration), you avoid creating unnecessary spaces inside your tag.
By using an inline condition statement, you avoid unnecessarily declaring a variable into the global scope. If you declare the selected string as a variable, as #independent.guru does, it will be declared/overwritten and used only once on every iteration; this can only decrease performance.
Each programmer will have their own preferences about "readability", "brevity", "consistency", and "performance" and may elect to construct their html using any mixture of the above techniques.
As a general rule, I don't bother to declare a variable that I will only use once. In my personal preference hierarchy, brevity, consistency, and performance always come before readability.
Some of the above points may seem like micro-optimizations, but for a canonical question, it is reasonable to include discussion on performance as any of the listed methods may be copy-pasted directly into projects.
If the first code block was too compact, here are two other versions that spread out the method over multiple lines without generating any extra variables:
Separated shorthand if/else syntax:
echo "<select name=\"select\">";
foreach($options as $text => $value){
echo "<option value=\"$value\"";
echo $selected == $value ? " selected" : "";
echo ">$text</option>";
}
echo "</select>";
Standard if conditional:
echo "<select name=\"select\">";
foreach($options as $text => $value){
echo "<option value=\"$value\"";
if($selected == $value){
echo " selected";
}
echo ">$text</option>";
}
echo "</select>";
All of the above versions of the same method will create this rendered html:
When the page is loaded:
When the select element is opened:
The source code will look like this:
<select name="select"><option value="xxs">Extra, Extra small</option><option value="xs">Extra small</option><option value="s">Small</option><option value="m" selected>Medium</option><option value="l">Large</option><option value="xl">Extra Large</option><option value="xxl">Extra, Extra Large</option></select>
This is the source code tabbed out for easier reading:
<select name="select">
<option value="xxs">Extra, Extra small</option>
<option value="xs">Extra small</option>
<option value="s">Small</option>
<option value="m" selected>Medium</option>
<option value="l">Large</option>
<option value="xl">Extra Large</option>
<option value="xxl">Extra, Extra Large</option>
</select>
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.
I have a php file with 2 arrays in it
//script containing all the rublics and subrublics
$rublic[0]='rublic1';
$rublic[1]='rublic2';
$rublic[2]='rublic3';
$rublic[3]='rublic4';
$rublic[4]='rublic5';
$subrublic[0]='subrublic1';
$subrublic[1]='subrublic2';
$subrublic[2]='subrublic3';
$subrublic[3]='subrublic4';
$subrublic[4]='subrublic5';
?>
The elements of these arrays are shown in the drop-down box. What I need to do is to grab the element which the user chose from the box and write the index number of the choice selected into a database field. How could I do that?
I will post my code here even though I realize that my approach to this problem is completely wrong from the start :(
//add the index number of the rublic and the subrublic to the db
include('rublics.php');
if(isset($_POST[' article_type']) && ($_POST['article_type'] != '0')){
$rublic_selected = $_POST['article_type'];
for($count_rublic=0; $count_rublic<=10; $count_rublic++){
if($rublic_selected == $rublic[$count_rublic]) {
$rublic_selected = $count_rublic;
}
if($rublic_selected == $subrublic[$count_rublic]){
$rublic_selected = $count_rublic;
}
}
} else {
echo 'You did not make the selection. Please choose the type of the article.';
}
Your dropdown can/should use the index numbers for the value attribute on the option elements. Ie:
<select id="article_type" name="article_type">
<option value="0">rublic1</option>
<option value="1">rublic2</option>
<option value="2">rublic3</option>
<option value="3">rublic4</option>
<option value="4">rublic5</option>
</select>
Then when the form is POSTed to your PHP script, you will already have the correct index number to write to the database.
Try this, it should be a good start:
$rublic[0]='rublic1';
$rublic[1]='rublic2';
$rublic[2]='rublic3';
$rublic[3]='rublic4';
$rublic[4]='rublic5';
$subrublic[0]='subrublic1';
$subrublic[1]='subrublic2';
$subrublic[2]='subrublic3';
$subrublic[3]='subrublic4';
$subrublic[4]='subrublic5';
//$user_input = 'rublic3';
$user_input = 'subrublic4';
$options = array('rublic', 'subrublic');
foreach($options as $option_key => $option_value)
{
foreach($$option_value as $key => $value)
{
if($value == $user_input)
{
echo 'found it at ', $option_value, ' ', $key;
break;
}
}
}
Basically, I loop through both arrays until I find the string that matches the correct user input and return the name of the array it was found in (rublic or subrublic) plus the index of that array.
here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));