Hold country value when submit - php

<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

Related

PHP concatenation $i in jQuery

Bit of a strange one, I have a webpage that iterates through a set number of times using while ($i <= 21):. During this iteration I have a dropdown in each which displays some values I pulled from a database, at this point that specific value doesn't matter but the id of each dropdown uses the value of $i. For example:
<select name="dropdown<?php echo $i; ?>" id="dropdown<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
What I am then wanting to do is take the value selected from that dropdown and place in another field that also has the id corresponding to the iteration number, for example:
<textarea name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>"></textarea>
I am using the following code for the jQuery to get the value from the dropdown and put it into the textarea:
<script>
$("#dropdown<?php echo $i ?>").on("change",function(){
//Getting Value
var selValue = $("#dropdown<?php echo $i ?>").val();
//Setting Value
$("#textfield<?php echo $i ?>").val(selValue);
});
</script>
However it doesnt seem to like the use of <?php echo $i ?> part as if i replace that with for example 2 or 3 then it works for that iteration.
I have tried setting the variable in PHP like: $textfield= 'textfield'.$i; and the using this as a whole in jQuery like this: $("#<?php echo $textfield ?>").val(selValue); but it doesnt like that either. Interstining if I change it to $textfield= 'textfield'.'2'; or $textfield= 'textfield2'; it works. Seems like it doesnt like my use of $i, is it the PHP concatenation that it doesnt like?
Anyone experienced this or know of a fix?
Huge fixes are required in your code but will explain the solution in minimal coding.
use array in name,dont use id,use class and data attribute to store the loop value as follows
<select name="dropdown[]" class="dropdown" data-id="<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<textarea name="textfield[]" class="textfield<?php echo $i; ?>"></textarea>
now in script single piece of code is enough to perform your operation with the help of class dropdown and dynamic class textfield
<script>
$(".dropdown").on("change",function(){
//Getting Value
var selValue = $(this).val();
var dynamic_id = $(this).data('id');
//Setting Value
$(".textfield"+dynamic_id).val(selValue);
});
</script>

php, get data from HTML select options, store them in variables and perform something

first, i've got a select option in a HTML document
<form action="Journey.php" method="post">
<select name = "Startpoint">
<optgroup label = "Start point">
<option value = "GrimesDyke">GrimesDyke</option>
<option value = "SeacroftRingRoad">SeacroftRingRoad</option>
<option value = "WykeBeck">WykeBeck</option>
<option value = "FfordeGrene">FfordeGrene</option>
<option value = "St.JamesHospital">St.JamesHospital</option>
.........
i determine the action is to pass the data using post method to Journey.php file in order to perform some algorithm, but when i click on the submit button in the browser it shown me my entire php code.... so i decided to run a few tests like this:
Journey.php
<?php
if(isset($_POST['submit'])){
$selected = $_POST['Startpoint']; // Storing Selected Value In Variable
echo "You have selected :" .$selected; // Displaying Selected Value
}
?>
this time, it displayed nothing, what i'm trying to do is, to store the Startpoint's value passed to the php file in a $selected variable and echo it on the screen, but it's still not working
i checked many examples online but honestly i can't see what i did wrong, please point out my mistake and show me how exactly i can make it right, thank you very much.
I wrote on php long time ago, but as I remember there is no 'submit' key in the $_POST table. Try to check for 'Startpoint' key instead.
This works for me:
<?php
if(isset($_POST['submit'])){
$selected = $_POST['startpoint']; // Storing Selected Value In Variable
echo "You have selected: " . $selected; // Displaying Selected Value
};
?>
<form action="" method="post">
<select name = "startpoint">
<optgroup label = "Start point">
<option value = "GrimesDyke">GrimesDyke</option>
<option value = "SeacroftRingRoad">SeacroftRingRoad</option>
<option value = "WykeBeck">WykeBeck</option>
<option value = "FfordeGrene">FfordeGrene</option>
<option value = "St.JamesHospital">St.JamesHospital</option>
<input type="submit" name="submit" value="Submit">
</form>

Displaying Select on GET

If I have a select form, for example:
<form action='?' method='get' name='form_filter' class="sortoptions" >
<select name="sort" >
<option value="None">None</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
I'm submitting using the GET method but need a way of when its been submitted and on the results page the option which was selected to be displayed.
So say if 'Price (High to Low)' is selected it will then be displayed in the select box on the results page after its been submitted
Any ideas?
Thanks!
When you will submit the form (assuming there is a submit button in your form), all data will be sent to PHP and you will retrieve all your data inside $_GET (the global var)
$_GET['sort']
will contain the value selected.
Then if you want to pre select, you just have to add some PHP code inside your HTML
<option value="PriceLow" <?php echo ((!empty($_GET['sort']) && $_GET['sort'] == 'PriceLow') ? 'selected="selected"' : '') ?>>Price (Low to High)</option>
You have to do the same for each option of the select.
That will allow you to preselect the good option after a first submit.
Solution 2:
If you don't wan to insert too much PHP inside your HTML code, you can store the posted value inside a javascript var and then, select the good option when the DOM is loaded (using a good JS library like jQuery for example)
Your HTML code:
<select name="sort" >
<option value="None">None</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
And some JS code in <script> tag
// Need jQuery !
$(document).ready(function() {
// Generate the selected var in JS using the value in PHP
var selectedOption = '<?php echo $_GET['sort']; ?>';
// Select the selected option and append the selected attribute
$("select[name=sort] option[value=" + selectedOption + "]").attr('selected', 'selected');
});
This code will automatically select the good option once the page is loaded.
Info: The good point is that you have a more clear and maintanable HTML code. The bad point is that if JavaScript is not enabled on the client, your automatic selection will not work (it will always work when you are using PHP to add "selected" in HTML). So you have to evaluate pro and cons and make your choice.
Note: you can leave the action empty instead of "?"
$_GET['sort']
in the submitted page will give you the selected option. And to check whether the form has been submitted:
if(isset($_GET['submit'])) {
// do something with the result
}
where 'submit' is the name of your submit button.
Try this code, it's probably what you would want. I assume you're writing it in your .php files or your other extensions, perhaps .html have php code enabled in them (maybe via .htaccess file)
<?php if (isset($_GET['sort'])){ ?>
<?php $sel= $_GET['sort']; # format? ?>
<strong><?php print($sel);?></strong>
<?php } ?>
<form action='' method='GET' name='form_filter' class="sortoptions" >
<select name="sort" >
<?php
$ff = Array(
'None' => 'None',
'PriceLow' => 'Price (Low to High)',
'PriceHigh' => 'Price (High to Low)',
'NameAZ' => 'Name (A-Z)',
'NameZA' => 'Name (Z-A)',
);
?>
<?php foreach ($ff as $v => $t) {?>
<option value="<?php print($v);?>" <?php if (isset($_GET['sort']) && ($_GET['sort'] == $v)) print('selected="selected"');?>"><?php print($t);?></option>
<?php } ?>
</select>
<input name="submit" type="submit" />
</form>

get selected item from a dropdown list and save it to a php variable

I have a dropdown list(in a php file and without form tag)
print "<select id="animal" onchange="getSelectedItem(this.value)">
<option value = "Dog"> Dog </option>
<option value = "Cat"> Cat </option>
</select>";
and a variable $selAnimal
and a javascript function
function getSelectedItem(opt){
//$selAnimal = opt <- how do i do this?
}
As much as possible I wouldn't like the page to reload so I avoid putting this inside a form and submitting as I select. I can't get to make $.post method work. I know for a fact that this cannot be directly done since php is server side and javascript is client side.
I also thought of putting the selected value inside a hidden component(span or something) and get the value from it. But I have no idea how to get it from the component. I've also seen use of AJAX or jquery but I'm not really knowledgeable enough.
I need to save this value to the php variable since I'll be using it as basis for the options in my second dropdown. For example, if I choose Dog, the dropdown list would have dog breeds as options.
I've spent days looking for possible solutions everywhere. Help would be very much appreciated. Thank you!
here is the solution
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#animal').change(function(){
$.post('loadbreeds.php', { animal:$('#animal').val() },
function(data){
$('#breedList').html(data);
});
});
});
</script>
<form method="post" >
<div id="animalList">
<select id="animal" name="animal">
<option value="">--Select--</option>
<?php if (!empty($animals)) { foreach ($animals as $value) { ?>
<option value="<?php echo $value['animalKey']; ?>"><?php echo $value['animalName']; ?></option>
<?php }} ?>
</select>
</div>
<div id="breedList">
<select id="breed" name="breed">
<option value="">--Select--</option>
</select>
</div>
<input type="submit" value="Submit" />
</form>
code for loadbreeds.php
$animalKey = $_POST['animal'];
$breeds = selectByKey($animalKey); // code for selecting breeds
<select id="breed" name="breed">
<option value="">--Select--</option>
<?php if (!empty($breeds)) { foreach ($breeds as $value) { ?>
<option value="<?php echo $value['breedKey']; ?>"><?php echo $value['breedName']; ?></option>
<?php }} ?>
</select>
You cannot have the variable available to the same file since PHP declares all its variables before the JS even starts. You can however simply redirect the user to a new file where the variable is available.
Use something like this:
function getSelectedItem(opt){
location.href = location.href + "?selAnimal=" + opt;
}
In PHP, now you can use the selAnimal variable to display something different, like this:
$selectedAnimal = $_GET["selAnimal"];
if($selectedAnimal == "dog"){
// Whatever you want to do now
}
A better way would be to use POST with forms, but this should work fine for you as well.
Try the following, to rebuild the second dropdown:
http://jsfiddle.net/kAY7M/59/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
print "<script type=\"text/javascript\">var AnimalTypeList = [\"Dog1,Dog2,Dog3,Dog4\",\"Cat1,Cat2,Cat3,Cat4\"];</script>";
<script type="text/javascript">
$("#animal").change(function () {
var sel = $("#animal").prop("selectedIndex") - 1;
var list = AnimalTypeList[sel].split(",");
var Counter = list.length;
$("#type").children().remove();
for (var i = 0; i < Counter; i++) {
$("#type").append("<option value = '" + list[i] + "'> " + list[i] + "</option>");
}
})
</script>
I could do a pure Javascript only version too, but that is a bit more code.

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>

Categories