Dropdownlist value is not getting selected. - php

Below is my code. It is Editor for user profile page as admin. I want to show to as selected. I read answers here. I tried, but it's not working for me. Whenever it comes close, it shows me BLANK in dropdown list.
<select name="city">
<?php
foreach( $province_array as $name)
{
if($name == $city )
{
echo '<option '.'value="'.$name.'"'.'selected="selected"'.'>'.$name.'</option>';
}
else
{
echo '<option '.'value="'.$name.'"'.'>'.$name.'</option>';
}
}
?>
and here
$city = $row['city'];
Suggestions plz!!

You should add a few more spaces here. Change this:
echo '<option'.'selected="selected"'.'>'.$name.'</option>';
to this for example:
echo '<option '.'selected="selected"'.'>'.$name.'</option>';

I think what you need to do is put a space between the opening of your <option> tag and the selected attribute. Check our your HTML source in the browser after you page has rendered.
<select name="city">
<?php
foreach( $province_array as $name)
{
if($name == $city )
{
echo '<option'.' selected="selected"'.'>'.$name.'</option>';
}
else
{
echo '<option'.' value="'.$name.'".'>'.$name.'</option>';
}
}
?>

Your echo statements are poorly constructed. There's no spaces between tag names and attributes. Try:
if($name == $city )
{
echo '<option selected="selected">'.$name.'</option>';
}
else
{
echo '<option value="'.$name.'">'.$name.'</option>';
}

echo '<option'.'selected="selected"'.'>'.$name.'</option>';
here option and selected is not seperated. You can insert a blank btw them :
echo '<option'.' selected="selected"'.'>'.$name.'</option>';
make it for others too

Appending a string that way always features a high level of risk that you may forget a space somewhere so I personally think that putting a string that needs single quotes inside double quotes like this:
echo "<option selected='selected'>".$name."</option>";
This makes it look so much more like normal HTML

Related

html multiple select chosen js submit form

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");

Echo option value with selected

Im tryin to fix when i press my search button. That the selected search from my option field remains selected. But at the moment it automaticly picks the first field of the options in my form.
First one is hardcoded and it works.
<option value="HS" <?= ($nickval == 'HS' ? 'selected="selected' : '')?>>Homer Simpsons</option>
But then i wanted to echo out option value from database so its not hardcoded.
<?php
while(db2_fetch_row($queryexe)) {
echo "<option value='$pin'>$fullname</option>";
}
?>
And now when i want to add if its selected i tried to solve it like this.
echo "<option value='$pin'($nickval == '$pin' ? 'selected='selected'' : '')>$fullname </option>";
This is how i get my pin
$pin = db2_result($queryexe, 'P510PIN');
This is how i get my $nickval
$nickval = $_GET["int"];
Any suggestions what im doin wrong? Sorry if im unclear but i've tried my best
Aside from quoting errors indicated in the syntax highlighting...
You're trying to execute PHP code inside of a string:
echo "<option value='$pin'($nickval == '$pin' ? 'selected='selected'' : '')>$fullname </option>";
Variable interpolation is one thing, but code inside of a string isn't going to automatically execute. It's just a string being echoed to the page. (Check the page source and see what's actually being emitted to the browser.)
Separate the strings from the code which builds the strings:
echo "<option value='$pin' " . ($nickval == $pin ? "selected='selected'" : "") . ">$fullname </option>";

How to get the complete value of an option tag?

I have this code using php
<select id="sem" name="y[]">
<option>Year</option>
<?php
$petsa = new DateTime();
$yr=$petsa->format('Y');
$a=$yr+1;//2015
$b=$yr-1;//2013
for($y=$b;$y<=$a;$y++)
{
$bb = $y+1;
echo '<option value="'.$y.'"'.'-'.$bb;
if(isset($_POST['y'])){
if (in_array($y."-".$bb,$_POST['y'])){
echo 'selected="selected"';
}
echo '/>'.$y."-".$bb;
}else
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
echo "</option>";
}
?>
</select>
if(isset($_POST['submit'])){
$sem= $_POST['sem'];//this is from other field
foreach ($_POST['y'] as $yer);
$osql2 = "INSERT INTO sy VALUES('$sem','$ss')";
if (mysql_query($osql2)){
echo "Successfully Added!";
}
This code work well almost but the problem is when i call the value of the option tag it just give me this value $ss=2014 and it should be like this $ss=2014-2015
what is wrong with my code? that code generate SY from 2013-2014 to 2015-2016
please help me.
Look at the generated HTML. Look at where the quotes around the attribute value are. They are currently very wrong.
Stop trying to generate HTML by mashing together lots of different strings. It becomes very hard to see what is going on.
$value = $y . "-" . $bb;
?>
<option value="<?php echo htmlspecialchars($value); ?>">
<?php echo htmlspecialchars($value); ?>
</option>
<?php
I suspect it's your use of quotes here:
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
I would change it to this:
echo "<option value ='$y"."-"."$bb"."'>".$y."-".$bb;
I have moved the second ' to just before the > of the opening option tag.
The single quote ' was for the option tag, and the double quote " was for the PHP string, you were simply cutting the value for option short

Retaining dropdown selection on postback creates empty options

I want to retain the users dropdown selection after the form has been submitted, however, since I added the code to do this it has created empty options in my dropdown list (even before anything is submitted). What is happening and how can I rectify it? Any help is very much appreciated.
$sals = array('Mr','Mrs','Miss','Dr');
<label>Salutation: </label>
<select name='mysal'>
<?php
foreach ($sals as $sal) {
echo "<option value='$sal'";
if($sal == #$sal_conf) echo 'SELECTED';
echo ">".$sal."<option />";
}
?>
If submit button (omitted here) is pressed:
if (isset($_POST['submit']))
{
$sal_conf = $_POST['mysal'];
}
Opening the drop down list look like this
Mr
Mrs
Miss
Dr
There is an empty selection after each option.
Give it a try.
<?php
foreach ($sals as $sal) {
$selected = ($sal == $sal_conf) ? ' SELECTED' : '';
echo '<option value="'.$sal.'"'.$selected.'>'.$sal.'</option>';
}
?>
You have not closed your
<option></option>
i find it cleaner to use curly braces {} when I have inline variables instead of closing the string when am using double quotes.
foreach($sals as $sal){
echo "<option value={$sal}";
if($sal == #$sal_conf) {echo "SELECTED "; }
echo " >{$sal}<option />";
}

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