get selected multiple value in textarea - php

I have a db_field (shortcode) that returns a string when submited query. the value from that return is AB,EF,GH (exactly this!
The second part is that i have a textarea with a list of that shortcodes. So i trying to highlight (selected) the same macthed elements.
for example:
$String_in_Database = AB,EF,GH;
Wish to have that:
<select name="Country[]" id="Country" multiple="multiple" size="5">
<option value="AB" selected>AB</option>
<option value="CD">CD</option>
<option value="EF" selected>EF</option>
<option value="GH" selected>GH</option>
......
</select>
This is how i generate the options:
<?php $MyArray = $settingsUser['set_disallowcountries']; ?>
<?php foreach($disallCountry as $key => $value) { ?>
<option value="<?php echo $value['short'] ?>" <?php if(is_array($value['short'], $MyArray)) { echo 'selected'; }?>><?php echo $value['long'] ?></option>
<?php } ?>

Maybe you want to explode this string into array?
$MyArray = explode(",",$String_in_Database);

Im slightly unsure to the question, so you want to check if the user has the selected country and have it selected in the option dropdown/box?
<?php
$userSelected= explode(",", $string_in_database);
$allCountries = array('AA', 'BB', 'CC');
foreach($allCountries as $country)
if(in_array($country["short"], $myArray){
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="'.$country["short"].'" '.$selected.'>'.$country["long"].'</option>';
}
With this, if the user string from the database (im guessing that is the users settings) is the same as AA, BB or CC, they will be selected, if it is not, they won't be selected.
To my knowledge I think this should work, I may be wrong as I have not tested it though. Just my thoughts!

Related

do not show duplicate values in my drop down box

I need some help with my logic here. I am populating a value from the database in my select box.
If it exists, I echo the value else i display the default options.
Now, for example if the value from the database is New Jersey, I do not want to display New Jersey for the second time in my drop down box. How do I do that?
<select name="location" class="field" >
<option value="<?php if(!empty($get_location)){ echo $get_location; } ?>"><?php if(!empty($get_location)){ echo $get_location; }?></option>
<option value="New Jersey">New Jersey</option>
<option value="New York">New York</option>
<option value="California">California</option>
</select>
You make an if statement in every option field and check if the value from the database matches the value of the option field and if it does so you echo "selected=\"true\"" to the option field.
For a code example see my answer for this question:
retieve data from mysql and display in form
If you only want your database values to be shown:
<?php
// You populate an array with the locations from your database
// As an example:
$options = array(1=>'New Jersey',2=>'Los Angeles');
$html = '<select name="locations">';
foreach($options as $id => $option)
{
$html .= '<option id="'.$id.'">'.$option.'</option>';
}
echo $html.'</select>';
?>
If you want something special to happen to your database values, but still load the default values too:
<?php
// You populate an array with the locations from your database
// As an example:
$options = array(1=>'New Jersey',2=>'Los Angeles');
// Compare against your full list of locations
// As an example:
$locations = array(1=>'New Jersey',2=>'Los Angeles',3=>'California',4=>'London');
$html = '<select name="locations">';
foreach($options as $id => $option)
{
if(array_key_exists($id,$locations))
{
// Enter your magic
}
}
echo $html.'</select>';
?>
I would change your php code slightly to add defaults and then you can filter and remove duplicates with jQuery. If there are lots of options this might not be the best solution tho...
php
<select name="location" class="field">
<?php if(!empty($get_location)): ?>
<option value="<?php echo $get_location; ?>">
<?php echo $get_location; ?>
</option>
<?php else: ?>
// Defaults
<?php endif; ?>
</select>
jQuery
var removeDup = function($select){
var val = '';
$select.find('option').each(function(){
if ($(this).val() === val) { $(this).remove(); }
val = $(this).text();
});
};
removeDup($('#yourSelect'));
Get your locations in one request to the database, add them to an array together with the defaults, if only one location do as below, if several locations parse them into an array and merge them with the defaults, do an array_unique to get rid of duplicates and output the array in a loop.
<select name="location" class="field">
<?php
$output = array(1=>'New Jersey', 2=>'New York', 3=>'California', 4=>$get_location);
$options = array_unique($output);
foreach($options as $key => $value) {
echo '<option value="'.$value.'">'.$value.'</option>';
}
?>
</select>

Using PHP $_POST to remember a option in a select box?

I have a form which POSTs to itselft so the user can do things that you would find in a Shopping Cart.
e.g. Increase quantity, select postage type.
My problem is for my form Select element called "postage" whenever the form reloads itself , it forgets what was selected.
All my other fields remember their values using this:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value to automatically select the option in the select field that was done by the user?
I tried this:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
and this
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
Thanks
You almost got it. You need to set the attribute selected="selected" (the exact form you need technically depends on your HTML doctype, but this is a safe default) on the <option> element if and only if the value of $postage equals the value of the element. So:
<select name="postage">
<option value="foo"
<?php if ($_POST['postage'] == "foo") echo 'selected="selected" '; ?>
>
</select>
Note that this violates the DRY principle because you now have two occurrences of the string "foo" in there, so it's a prime candidate for refactoring. A good approach would be to keep value/text pairs in an array and iterate over it with foreach to produce the <option> tags.
You need to foreach through all the options.
Make an array with all the dropdown options, loop through that, and compare with what is stored in post.
E.G.:
<?php
$aDropd = array("apple","orange","banana");
echo "<select>";
foreach($aDropd as $sOption){
$sSel = ($sOption == $_POST['postage'])? "Selected='selected'":"";
echo "<option $sSel>$sOption</option>";
}
echo "</select>";
no its not working at all..you need to put some kind of loop for that.
For Example : foreach($record => $values){
if($values == $_POST['postage']){
$selected = "selected='selected' ";
}else{
$selected = "";
}
}
<input name="postage" value="1" <?=$selected?> >
EDITED:
if($_POST['postage'] == 1){
$selected1 = "selected='selected' ";
}else if($_POST['postage'] == 2){
$selected2 = "selected='selected' ";
} and so on..........
<select name="postage">
<option value="1" <?=$selected1;?> />
<option value="2" <?=$selected2;?> />
</select>
I think this may be helpful to you..you can ask me if anything else needed...
Thanks.
The value of selected should be selected
<select name="postage" value="1" <?php echo (($_POST['postage'] == 1)?'selected="selected"':''); ?> >
Your html syntax is wrong. The correct way to write the html is like this:
<select>
<option value ="<?php echo $_POST['postage']; ?>" selected="selected"></option>
</select>
You can also make it shorter:
<select>
<option value ="<?=$_POST['postage']; ?>" selected="selected"></option>
</select>
<select name="foo">
<option value="1" <?php echo strcmp($_POST['foo'],"1")==0?"selected=\"selected\"":"" ?>>option1</option>
<option value="2" <?php echo strcmp($_POST['foo'],"2")==0?"selected=\"selected\"":"" ?>>option2</option>

make a value selected in drop down when editing

I am adding a feature to edit the ads a user puts. For that I want to make the value selected which is selected by the user when he entered the values . How can I implement this?
<div class="nm">
Category
</div>
<div class="fl">
<select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
<option value="">---Select Category---</option>
<option value="real_estate">Real Estate</option>
<option value="hotels_resturants">Hotels and Resturants</option>
<option value="car">Car Rental</option>
</select>
</div>
Add the selected HTML <option> attribute, in XHTML it is selected="selected".
<option value="value" selected>title</option>
^^^^^^^^
Documentation: http://www.w3.org/TR/html4/interact/forms.html#h-17.6.1
I mean how will I know which one should be selected..it will be different for different users . I wnt it to be selected which user selects during adding the ad
That depends on your code. You can do this with an array with all value/title pairs (value => title) and the value which is selected. Then when key (value) equals the selected one, the attribute is added in output. As it's an array it's easy to iterate over it.
$otpions = array(
'a' => 'A',
'b' => 'B',
);
$selected = 'b';
echo '<select>';
foreach ($options as $value => $title)
{
printf('<option value="%s" %s>%s</option>',
$value, $selected == $value ? 'selected' : '', $title);
}
echo '</select>';
okay lets assume you fetch value from db and that select box value is in $select variable then you've to write
<option <?php if($select=="real_estate") { echo "selected='selected'"; } ?> value="real_estate">Real Estate</option>
<option <?php if($select=="hotels_resturants") { echo "selected='selected'"; } ?> value="hotels_resturants">Hotels and Resturants</option>
<option <?php if($select=="car") { echo "selected='selected'"; } ?> value="car">Car Rental</option>
You can use this magic function
function __selectedDb($ctrlValue,$dbValue)
{
if($ctrlValue == $dbValue)
return "selected='selected'";
else
return "";
}
like
<select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
<option value="" <?php echo __selectedDb("","$cat")?>>---Select Category---</option>
<option value="real_estate" <?php echo __selectedDb("real_estate","$cat")?>>Real Estate</option>
<option value="hotels_resturants" <?php echo __selectedDb("hotels_resturants","$cat")?>>Hotels and Resturants</option>
<option value="car" <?php echo __selectedDb("car","$cat")?>>Car Rental</option>
</select>
I write in core php please convert php code to smarty

How insert into database both value and content?

How insert both value and content into database separate separate column. Its a dropdown menu. Like
<select name="name" id="name">
<option value="000">Please select</option>
<option value="calendar.gif">Animal Welfare</option>
<option value="calendar1.gif">Art and Cultural</option>
<option value="calendar2.gif">Career Related</option>
</select>
For the instance "Animal welfare", want to insert "calendar.gif" to one column and "Animal welfare" to another column.
Store the option => value combinations in an array. You can then use this array for both inserting and displaying, eg
$options = array (
'calendar.gif' => 'Animal Welfare',
'calendar1.gif' => 'Art and Cultural',
'calendar2.gif' => 'Career Related'
);
if (isset($_POST['name']) && array_key_exists($_POST['name'], $options)) {
// valid option submitted
$key = $_POST['name'];
$value = $options[$key];
// now you can insert $key and $value
}
// to display
?>
<select name="name" id="name">
<option value="">Please select</option>
<?php foreach ($options as $key => $value) : ?>
<option value="<?php echo htmlspecialchars($key) ?>">
<?php echo htmlspecialchars($value) ?>
</option>
<?php endforeach ?>
</select>
Only the string in the value attribute is sent to the server.
If you wanted the text node as well, you'd need to use JavaScript (possibly XHR).
An example using JavaScript might be...
var selectedOptionTextNode = document.createElement('input');
selectedOptionTextNode.type = 'hidden';
selectedOptionTextNode.name = 'selected-text-node';
document.body.appendChild(selectedOptionTextNode);
document.getElementsByTagName('select')[0].addEventListener('change', function() {
selectedOptionTextNode.value = this.options[this.selectedIndex].innerHTML;
}, false);
jsFiddle.
Now the text node will also be submitted to the server.
However, by far the best way to do this is per Phil's answer, i.e. associate the keys with values on your server.

How to Keep the selected value of the select box after Form POST or GET

Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>

Categories