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.
Related
this is the code
<select class="country" name="country" id="country" >
<option value="" disabled selected>Choose Country</option>
<option value="in" >India</option>
<option value="jp" >Japan</option>
</select><br/>
I want to set the user selected value on form when submitted. Now when user select a value it get back to "Select country" when submit button pressed.
and how can I enter full country name into database? as of now it enter the value which is "in" or "jp"?
thanks for help.
My recommended solution is to have an array of country codes mapped to country names. This will be used to create the options using a loop, to find the full country name and to validate the user input.
PHP
$countries = array(
'in' => 'India',
'jp' => 'Japan',
);
$selectedCountryCode = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$selectedCountryCode = isset($_POST['country']) ? $_POST['country'] : '';
if(isset($countries[$selectedCountryCode])){
$selectedCountryName = $countries[$selectedCountryCode];
// insert $selectedCountryName
} else {
// validation error - country not found, do not insert
$selectedCountryCode = ''; // reset because it was invalid
}
}
HTML
This includes the select tag with the options produced from a loop. In the loop, the posted country is checked and selected if necessary. The user input will simply contain the county code in or jp, and the PHP above will map that to the full name for insertion.
<select class="country" name="country" id="country" >
<option value="" disabled>Choose Country</option>
<?php foreach($countries as $code => $countryName): ?>
<option value="<?php echo htmlspecialchars($code); ?>" <?php if($code == $selectedCountryCode){ echo 'selected'; } ?>><?php echo htmlspecialchars($countryName); ?></option>
<?php endforeach; ?>
</select><br/>
how can I get the selected key and value of a HTML select box using php?
<select>
<option value="KEY">VALUE</option>
</select>
php code ?
With PHP, it is not straight forward.
However, with use of array you can achieve it.
Take and array of all options in a common function:
$options = array();
$options[1] = 'one';
$options[2] = 'two';
$options[3] = 'three';
Display drop down like this:
<select name="opt">
<option value=""></option>
<?php
if (! empty($options)) {
foreach ($options as $key => $val) {
?>
<option value="<?php echo $key;?>"><?php echo $val;?></option>
<?php
}
}
?>
</select>
And where the form is posted, again get the array.
//$options : fetch from common function.
if (isset($_POST['opt'])) {
echo "key: " . $_POST['opt'];
echo "<br/>";
echo "value: " . isset($options[$_POST['opt']]) ? $options[$_POST['opt']] : '';
}
You must do like this
<form class="" action="receiver.php" method="post">
<select name="mykey">
<option value="KEY">VALUE</option>
</select>
</form>
In your receiver.php do in this example
$keys = $_POST['mykey'];
Name of the select is the key and option is the value.
<select name="KEY">
<option value="VALUE">VALUE</option>
<option value="VALUE_2">VALUE</option>
</select>
On submit you will get a KEY => VALUE pair in $_GET or $_POST (whatever you use to handle the request)
page1.html:
<form action="page2.php" name='add' method="post">
<select name="foo">
<option value="my_value">my_value</option>
</select>
<input type='submit' name='submit'/>
</form>
page2.php:
<?php
$result = $_POST['foo'];
echo "result = ".$result."<br>";//output: result = my_value
?>
Using PHP, you could use this:
Put Key and Value as POST data, delimited with a symbol, for example '/'.
HTML:
<select name="myselect">
<option value="KEY/VALUE">VALUE</option>
</select>
Then in PHP, separate that key with explode() function.
PHP:
$pair = explode("/", $_POST["myselect"]);
$key = $pair[0];
$value = $pair[1];
print "Key: $key<br />";
print "Value: $value<br />";
Let's say you have form like this
<select name="country">
<option value="IN_India">India</option>
<option value="CN_China">China</option>
<option value="AE_UAE">UAE</option>
</select>
Upon submitting it, your $_POST would look something like this
print_r($_POST);
Array
(
[country] => IN_India
}
Now explde your $_POST data and fetch values like this
$data = explode('_', filter_input(INPUT_POST, 'country'));
print_r($data);
Array
(
[0] => IN
[1] => India
)
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!
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>
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