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
)
Related
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 found this code below and it works perfect for what I want BUT I have over 30 options is there something else I can do to shorten the code?
<html>
<body>
<form method="post" action="?">
<select name="dropdown">
<option value="Jehzeel1">Jehzeel1</option>
<option value="Jehzeel2">Jehzeel2</option>
<option value="Jehzeel3">Jehzeel3</option>
</select>
<input type="submit" value="submit">
</form>
</body>
</html>
<?php
switch ($_POST['dropdown']) {
case "Jehzeel1":
echo "Jehzeel likes apples";
break;
case "Jehzeel2":
echo "Jehzeel likes bananas";
break;
case "Jehzeel3":
echo "Jehzeel likes oranges";
break;
?>
It's easier to create a mapping array:
$map = array(
'Jehzeel2' => 'Jehzeel likes bananas';
'Jehzeel3' => 'Jehzeel likes oranges';
);
echo $map[$_POST['dropdown']];
Although you may want to think twice about your code structure, this looks like a bad practice.
Short way:
<?php
$fruits = array('apples', 'oranges', 'bananas');
?>
<form method="post">
<select name="dropdown">
<?php foreach ($fruits as $fruit) : ?>
<option value="<?php echo $fruit ?>"><?php echo $fruit ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="submit" />
</form>
<?php
if (in_array($_POST['dropdown'], $fruits)) {
echo 'Jehzeel likes ' . $_POST['dropdown'];
}
?>
EDIT
You can use urls by slightly changing the array and the if statement:
$urls = array('url1' => 'http://www.facebook.com/', 'url2' => 'http://www.google.com/', 'url3' => 'http://www.yahoo.com/');
if (isset($urls[$_POST['dropdown']])) {
echo 'URL: ' . $urls[$_POST['dropdown']];
}
Consider changing the values of your options to something like:
<select name="dropdown">
<option value="apples">Jehzeel1</option>
<option value="bananas">Jehzeel2</option>
<option value="oranges">Jehzeel3</option>
</select>
Then simply in your php code:
$valid_fruits = array("apples", "bananas", "oranges");
$fruit = $_POST['dropdown'];
if(in_array($fruit,$valid_fruit))
echo "Jehzeel likes $fruit"
I hope it helped. Cheers
You could use an array with the values as the key, and the text as the value:
// array of key/value pairs
$text = array(
"Jehzeel1" => "apples",
"Jehzeel2" => "bananas",
"Jehzeel3" => "oranges",
);
// create your key from the post value, make sure it is actually set
$key = isset($_POST['dropdown']))? $_POST['dropdown'] : "";
// echo the value based on the key, if the key exists
$value = (array_key_exists($key, $text))? $text[$key] : "nothing";
// assuming all the text starts with "Jehzeel likes" you can sprintf the value
echo sprintf("Jehzeel likes %s.", $value);
Create an array with your options:
$DropdownLabels = array (
'dropdown1' => 'Dropdown1 Long Label',
'dropdown2' => 'Dropdown2 Long Label',
// ...,
);
And then use $DropdownLabels[$_POST['dropdown']] and test if it exists with array_key_exists($_POST['dropdown'], $DropdownLabels).
I'm trying to make this implode function work.
This is the form part, assume all the item has been selected.
<form method="post">
<select name="test1" multiple="multiple" id="test1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
<option value="5">item5</option>
</select>
</form>
The PHP part
<?php
$var1 = array();
$joinedString = array();
$var1 = $_POST['test1'];
$joinedString = implode(',', $var1);
?>
But The echoing part doesn't work, it gives me error, and only displaying only the first array value.
<?php
$echo $joinedString[0];
$echo $joinedString[1];
$echo $joinedString[2];
$echo $joinedString[3];
$echo $joinedString[4];
?>
Thank You guys, I'm quite new in programming. I always forgot that the code executed line by line, and always confused with variable and values, and yes, in real world I am also a clumsy & insignificant person.
<form method="post" action="sear.php">
<select name="test1[]" multiple="multiple" id="test1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
<option value="5">item5</option>
<input type="submit" name="submit" value="submit" />
</select>
</form>
<?php
$var1 = array();
$joinedString = array();
$var1 = $_POST['test1'];
$joinedString = implode(',', $var1);
echo $joinedString;
?>
After getting the post values it definitely works.... Try it...
Use
<select name="test1[]" multiple="multiple" id="test1">
In php file.
$var1 = isset($_POST['test1']) ? $_POST['test1']: 0 ;
print_r($var1); //gives array
foreach($var1 as $var) {
echo $var;
}
Change
<select name="test1" multiple="multiple" id="test1">
to
<select name="test1[]" multiple="multiple" id="test1">
And it's already an array
$var1 = $_POST['test1'];
$imploded = implode(",", $var1);
echo $imploded;
//FOR GETTING INDIVIDUAL ITEMS FROM array
echo $var1[0];
Implode is not getting any array. Its works on Array.
You are passing a string instead of an array. implode() turns an array into a string.
In your script, $_POST['test1'] will only contain the submitted value of the select box, not the entire set of values. Since $var1 contains only a string, implode() will error out.
Just look up this:
http://www.tizag.com/phpT/php-string-implode.php
And $ is used with variable.
You are trying to use implode your array using (,) but post array values does not contain values seperated by comma, therefore you will have to use foreach.
<?php
$var1 = array();
$joinedString = array();
$var1 = $_POST['test1'];
foreach($var1 as $values)
echo $values."<br/>";
?>
<form method="post">
<select name="test1[]" multiple="multiple" id="test1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
<option value="5">item5</option>
</select>
<input type="submit" >
</form>
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 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.