do not show duplicate values in my drop down box - php

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>

Related

Hold country value when submit

<label>Country <font color="8AC007">*</font> </label></td>
<td><select name="country" onchange="print_state('state',this.selectedIndex);" id="country"<?php
$sel_country = $myform->value('country');
if (isset($sel_country)) echo 'selected="selected"'; ?> />
<option value="<?php $myform->value("country"); ?>"/>Select country</option>
</select><br><?php $sel_country.'sample' ?>
<span class="error"><?php echo $myform->error("country"); ?></span>
I want to get hold with the country selected value when I submit form, instead filling the form from starting again. Here is the code Iam trying to get countries from a js file.
Apperciate your help
HTTP is stateless, so you have to put a little effort on keeping data around when moving from page to page. Seeing this as being a form with inputs (select in this case), you can use $_POST to get hold of your submitted value in the next page.
In this case you'd use $_POST['country']. If you want to keep the current form filled next time the page refreshes, make the form submit to the current page, then you'll have access to that value in $_POST.
Other ways to keep data around:
Sessions
Cookies
Database storage
But this require a little bit of additional coding in PHP.
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country"/>
<option <?php if($youroldval==$myform->value('country')){ echo 'selected="selected"'; } ?> value="<?php echo $myform->value("country"); ?>"/><?php echo $myform->value("country"); ?></option>
</select>
You must store your old value of form
Ok, if I am right you should do it as follows.
If you are posting your page to the server. You have the selected value. You store this and return this page. In that case I added bollow code and added $isSelected to the code. Normally it emtpy, but if the value is equal to the selected then you set selected='selected'.
<select name="country">
<?php
$countryList = array("USA", "UK", "France", "Germany", "India", "Netherlands");
$isSelected = "";
foreach($countryList as $country)
{
if($_POST["country"] == $country)
{
$isSelected = "selected='selected'";
}
echo "<option value='" + $country + "' " + $isSelected + ">" + $country + "</option>";
?>
</select>
If you are using jquery / Ajax, you have the selected value which stays selected because the page wont refresh :-) However, you can get the value by using javascript and get value from selectbox.
------ Edit
Mmm ok, I was in the illusion you had your array in php. However you get your collection from javascript. In that case you will get this as solution:
<script type="text/javascript">
var selectedCountry = "<?php echo $myform->value("country"); ?>";
</script>
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country">
/* This is generated by javascript */
</select>
Your javascript function will be like this:
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selectedCountry == country_arr[i])
{
option_str.options[option_str.length].setAttribute("selected", "selected");
}
}
}
----- Edit 2:
http://jsfiddle.net/eLProva/5mU76/ with filling and selecting the country

get selected multiple value in textarea

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!

PHP: Echo value of selected item from a dependable dropdown menu

I am currently working with a Dependable dropdown menu that functions with the help of jQuery and PHP. The values are being pulled of MySQL database. Is there away to php echo the selected value of a dependable drop down menu?
EXAMPLE
HTML/PHP
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Please add jquery.js.
your html code
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
//jquery code for source list
<script type="text/javascript">
$(document).ready(function(){
$('#gender').change(function() {
if ($(this).val()!='') {
$("#category").load("postfile.php",{gender_id: $(this).val()});
$("#category").removeAttr('disabled');
}
});
//code on change of sel_source
$('#category').change(function() {
if ($(this).val()!='') {
$("#colour").load("postfile.php",{category_id: $(this).val()});
$("#colour").removeAttr('disabled');
}
});
});
</script>
//postfile.php
//your mysql connection other things goes here
//code for category
$objDb = new PDO('mysql:host=localhost;dbname=dbname', 'ur_username', 'ur_password');
if(isset($_REQUEST['gender_id']) && !empty($_REQUEST['gender_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['gender_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
//code for color
if(isset($_REQUEST['category_id']) && !empty($_REQUEST['category_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['category_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
Hope this will help you.
You are going to have to write a JavaScript function that retrieves the selected value or option from the first HTML select field. This function commonly writes out a new URL path to the current page with the addition of some concatonated Get Variables:
<script type="text/javascript">
getSelectedOptionValue() {
// create some variables to store your know values such as URL path and document
var myPath = " put the URL path to the current document here ";
var currentPage = "currentPage.php";
// get the values of any necessary select fields
var carMake = document.getElementById("carMake").value;
// write out the final URL with the Get Method variables you want using concatnitation
var getMethodURL = myPath + currentPage + "?carMake='" + carMake + "'";
// function refreshes page using the function made URL
window.location.replace( getMethodURL );
}
</script>
Since the second select field is dependent on the first you have to assume that the user is going to make a selection from the first choice of options. This means that the function that retrieves the value of the primary select field must run in response to a change in the fields selection. For example
<select name="carMake" id="carMake" onchange="getSelectedOptionValue();">
Depending on how you have set up your DB, you may want either the value of the option tag or the string presented to the user between the option tags...this is up to you keeping in mind how you may re-query the information if your original record set hasn't already pulled up the necessary info to write the second set of select option tags.
To write out the second select field using php simply repeat the while loop you have used for the first. This time replace your SQL statement with a new one using a variable in which you have stored the value retrieved from the new URL using the get method
<?php
// here I am using the more generic request method although you could use the get as well
$carMake = $_REQUEST['carMake'];
sql_secondSelectField = "SELECT * FROM tbl_carModels WHERE carMake = $carMake";
// Run new query and repeat similar while loop used to write your first select field ?>

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