Adding error message when a specific drop down option is selected - php

Ok guys, Ive done some researching and can't find something that works to solve my problem even though I'm sure its a simple fix :)
I have a simple contact form in which the first line is a drop down selection. This drop down determines which employee the form is submitted to. I just want to make my default option of "Please Select Category" return an error message so that the submitter must go back and select one of the options to get the form sent. When nothing is selected, its creating a lot of junk mail to the default email.
Here is the drop down bit of code:
<tr>
<td><label for="sendTo">Category (required):</label></td>
<td>
<select id="sendTo" name="sendTo">
<option id="pleaseSelectcategory1" value="pleaseSelectcategory1">Please Select Category</option>
<option id="aftermarketCustomerservice" value="aftermarketCustomerservice">Aftermarket Customer Service</option>
<option id="technicalAssistance" value="technicalAssistance">Technical Assistance</option>
<option id="aftermarketSales" value="aftermarketSales">Aftermarket Sales</option>
<option id="performanceProducts" value="performanceProducts">Performance Products & Sales</option>
<option id="oemSales" value="oemSales">OEM Sales</option>
<option id="exportSales" value="exportSales">Export Sales</option>
<option id="generalFeedback" value="generalFeedback">General Feedback</option>
</select>
</td>
</tr>
I just need what to put in my html, if anything, to make this error message occur and in my php file. Thanks in advance!!

You should use a Javascript function to validate your form prior to posting the data. This is better for UX, and will prevent the form from even reaching the PHP post function.
In your form have the onsubmit field call a Javascript function:
<form name="form" id="form" action="" onsubmit="return validateForm()" method="POST">
and your Javascript function for checking the select box value:
// Basic form validation for select box.
function validateForm() {
if (document.getElementById("sendTo").value != null && docmument.getElementById("sendTo").value != "pleaseSelectcategory1") {
return true;
}
//Handle error message here.
alert("Please select a category");
return false;
}
You can also validate your form once the form gets posted in PHP with:
if ($_POST['sendTo'] === 'pleaseSelectcategory1') {
// Redirect back to form or do whatever
}

In pure JavaScript you can use the following function:
function checkCategory(){
if(document.getElementById('sendTo').value === 'pleaseSelectcategory1') {
alert("You need to select category");
//This is to ensure that the form doesn't get submitted.
return false;
}
}
Either use onclick="javascript:checkCategory();" on the button or the form itself onsubmit="javascript:checkCategory();"
In PHP you can just use:
if($_POST['sendTo'] == "pleaseSelectcategory1")
{
//However you want to handle the the fact the user selected the option
}

Related

retain select option values in php

I am unable to figure it out on how to retain select option value after submission. I have looked at various forums and self-help sites:
store drop down options in mysql database, PHP1
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
insert value of html select form into mysql database
Using $_POST to get select option value from HTML
Yet, when refresh the page after selecting the dopwdown options, it wasn't able to retain the last selected value:
Select PHP codes:
$dropdown = elgg_echo('<DIV align="left", >
<form method="post" action="Select.php">
<select name="mycustomFile" >
<option>Select Value..</option>
<option value="A">a</option>
<option value="B">b</option>
<option value="C">c</option>
<option value="D">d</option>
</select>
<p><input type="submit" value="Submit"</p>
</form>
</DIV>');
2nd Code: Select.php (where I perform $_POST[''] action)
<?php
/**
* Override the ElggFile
*/
class FilePluginSelect extends ElggObject {
protected function initializeAttributes() {
parent::initializeAttributes();
$this->attributes['customFile'] = "my_select";
}
public function __construct($guid = null) {
parent::__construct($guid);
}
public function customFile(){
//method to call on model to allow select option
//To post select option into mysql database
$selectOption =$_POST['mycustomFile'];
if(isset($selectOption)){
$sql = "INSERT INTO Entries (mycustomFile) VALUES (".$_POST['selectOption'].")";
}else { // User selected nothing
echo 'No options selected!';
}
}
}
Could someone please help to enlighten me what has gone wrong. Thanks
You're doing it completely wrong. You probably just should use Elgg data model and store your value in metadata unless you have very good reason to ignore framework and do stuff on your own.
First of all don't bother extending ElgObject, you're doing it completely wrong and don't really need it.
To retain selection, you have to read the value and mark tag with selected attribute.
You need to update also action of saving file to include new field value. To save it to metadata you just need to use EAV interface of the entity (you'll find example in http://learn.elgg.org/en/1.12/tutorials/blog.html). Than you can read it within the view you're extending
As for the select element itself, you should use existing input/dropdown view instead. It will save you some boilerplate code. Also no need to add tag as you should be extending existing form view. Views documentation is here: http://learn.elgg.org/en/1.12/guides/views.html
I strongly recommend starting your search in Elgg documentation first. Elgg does have some learning curve, but you want to learn the proper way for your code to be maintainable in future.
set mycustomFile to mycustomFile[] . Also don't post anything into the database without clearing it, its very dangerous.
update:
Your php for getting the value of the select form is correct. Your script isn't working for another reason. Here is a sample of retrieving the select fields data.
<?php
if(isset($_POST['button']))
{
echo 'select value: ' . $_POST['something'];
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="something">
<option value="a">some a</option>
<option value="b">some b</option>
<option value="c">some c</option>
</select>
<button name="button">
click
</button>
</form>
</body>
</html>

Error while getting select box value with php

I am currently working on a project where a user chooses an option from a select box and submits a form, the form is then processed by PHP, and the PHP code determines what the select box value is, and does something based on that value.
My select box is called combined_group and has two select values: philharmonic_orchestra and symphony_orchestra.
This is how I am checking the selected value:
if($_POST['combined_group'] == "philharmonic_orchestra"){
$_SESSION['semesterprice'] = "170";
$_SESSION['fullprice'] = "330";
}
if($_POST['combined_group'] == "symphony_orchestra"){
$_SESSION['semesterprice'] = "275";
$_SESSION['fullprice'] = "530";
}
But when PHP runs through this code, neither if statement is chosen. I know that the value of $_POST['combined_group'] is, in fact, either of those two values, just PHP isn't picking it up for some reason.
Anybody care to help?
EDIT: My HTML form code is as follows
<select name="combined_group" class="OBJ-1">
<option value="" selected="">Select One</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra ">Symphony Orchestra</option>
</select>
Client side
<select name="combined_group">
<option value="">Select an option</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra">Symphony Orchestra</option>
</select>
Server side
if (! isset($_POST["combined_group"]))
{
exit('not set');
}
if (trim($_POST["combined_group"]) == '')
{
exit('not selected');
}
if (trim($_POST["combined_group"]) == 'philharmonic_orchestra')
{
//business logic for 'philharmonic_orchestra'
}
else
{
//business logic for 'symphony_orchestra'
}
Most likely is a bad HTML syntax. Check if your option item has value attribute:
<option value="...">...</option>
The reason why your conditional statement is failing, is because of a space in your option's value.
<option value="symphony_orchestra ">
^ right there
What you will need to do is remove it:
<option value="symphony_orchestra">
^ deleted space
Technical sidenote:
Had your conditional statement been:
if($_POST['combined_group'] == "symphony_orchestra ")
^ notice the space
with the space before the quote, it would have worked.
Anything between quotes is considered and part of an element's value.

auto submit dropdown list in php

I want to create a dropdown list in a form and be able to submit/process it without pressing the submit button. I have
$cquery = 'SELECT * FROM tcat ORDER BY id ASC';
$cresult = mysql_query($cquery, $connection);
if(!$cresult){echo 'no result' . mysql_error();}
while($crow = mysql_fetch_array($cresult))
{echo $crow['cat'] . '</option><option>';}
?>
I would like to know if there is a way to make the default that is shown a different value aside the first or the last
even simpler, this should work too!
<select onchange="submit();">
<options ... >
</select>
To submit a form without having the user press a submit button, you can use JavaScript:
document.getElementById("form_id").submit();
To set a default selected option, you can do this:
<option selected="selected">Category Name</option>
Note that PHP will not auto-submit a form for you as it is a server-side language.
You have to use html and javascript and change your script to generate them accordingly:
<select name="aName" onChange="document.getElementById('yourFormId').submit();">
...
</select>

Remembering php form data to display currency all over a website

I've set up a currency conversion dropdown in a wordpress site.
The only thing missing is that every time I load another page, the currency will reset as the form selection was 'forgotten'.
Any ideas how to do this? I tried a suggested js cookie that I saw here, but it doesn't work.
This is what I got so far:
<form name="myform" id ="myform" method="post">
<select name="currency-select" id="sort" onchange="submitform();">
<option value="" selected="selected">Currency</option>
<option value="0">U.S Dollars (USD)</option>
<option value="1">Euros (EUR)</option>
<option value="2">British Pounds (GBP)</option> `
</select>
</form>
js:
function submitform()
{
document.myform.submit();
}
I tried using this code as recommended here but it doesn't really work out for me, I think I didn't do it the right way -
<?php
`session_start();`
if (isset($_POST['currency-select'])) {
$_SESSION['sort'] = $_POST['sort'];
}
?>
I added the $_SESSION to the form as well:
<option value="0" <?php if($_SESSION['sort'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
UPDATE
I've made a few tests. The session seems to be saved (as I echoed it on a few pages while refreshing etc.) I guess the only problem now is related to the form itself. Even with the right session number, I can't get it to select the right option.
I've tried two methods, but both does not work:
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo 'selected="selected"';?>>U.S Dollars (USD)</option>
or
<option value="0" <?php if($_SESSION['currency-select'] == "0") echo "selected";?>>U.S Dollars (USD)</option>
I'd store the selected value in a $_SESSION['selected_currency'] variable and the cross check and select it when the drop down is being populated with the currency list.
Assuming that the sessions are working, I will use something like below to keep the currency selected in your drop down.
<select name="currency">
<?php
foreach($currency as $value){
if($value->currency_code == $_SESSION['currency']){
echo "<option value='$value->currency_code' selected='selected'>$value->currency_name</option>";
} else {
echo "<option value='$value->currency_code'>$value->currency_name</option>";
}
}
?>
</select>
There could be shorter ways, I am using this for illustration purposes.
For permanent retain of data you only have a few possibilities, the easiest to implement are $_SESSION, $_COOKIE or in a Database.
You have two options to do that
1st is by adding a field to the options.php page and save your data then get back your data from the options.php for that you've to use update_option('nameOfField_form','nameOfFieldDb'); and get_option('nameOfFieldDb').
and 2nd option is by jquery.ajax(); method save your data in options.php
you may find these links helpful codex
get_option
update_option

Two drop down list values auto selected based on php session value

I have two drop down lists.
Second one is populated based on value chosen in the first one. I'm using Double Combo Script Credit By JavaScript Kit to do that (I am very bad with javascript).
I use this to filter results from my Mysql database.
The problem is that when user applies filter i want him to see what he applied (when page refreshes or user goes to other page) - those values should be seen as selected in both drop down lists. I can't figure out where i should place an event or something else.
I'm holding subcategory values from the second drop down list in php session :
if (isset($_SESSION['subcat']) && !isset($_GET['subcat'])){
$color= $_SESSION['subcat'];
}
elseif (!isset($_SESSION['subcat']) && isset($_GET['subcat']))
{
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
elseif (isset($_SESSION['subcat']) && isset($_GET['subcat'])){
unset($_SESSION['subcat']);
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
else {
$color= "";
};
I can echo selected in first drop down list, based on session value and that works, but a second one drop down list is not generated when page refreshes and i don't know where should i echo 'selected = "selected"' or maybe everything can be done only with javascript? Please help.
The code:
<div class="filter">
<form method="get" name="doublecombo" action="" id="filterform" >
<select name="example" id="exampl" size="1" onChange="redirect(this.options.selectedIndex)">
<option>All kinds</option>
<option>Women</option>
<option>Men</option>
</select>
<select name="subcat" size="1" id="subcategory">
<option value="lists.php">All colors</option>
</select>
<input type="button" name="test" value="Filter" onClick="go()">
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("All colors","list.php")
group[1][0]=new Option("Pink","list.php?subcat=1 ")
group[1][1]=new Option("White","list.php?subcat=2")
group[1][2]=new Option("Green","list.php?subcat=3")
group[2][0]=new Option("Black","list.php?subcat=12")
group[2][1]=new Option("Blue","list.php?subcat=13")
group[2][2]=new Option("Grey","list.php?subcat=14")
group[2][3]=new Option("Brown","list.php?subcat=15")
var temp=document.doublecombo.subcat
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
</form></div>
you could set a cookie to hold the selected value, so if the user selects there choice and refreshes, you would then check if the cookie exists and then populate the menus accordingly.
Update:
This will store the selected values and repopulate the select menus if the user refreshes the page.
First select added onkeup:
<select name="example" id="exampl" size="1" onchange="redirect(this.options.selectedIndex)" onkeyup="redirect(this.options.selectedIndex)">
for the second select and as follows to check for changes
<select name="subcat" size="1" id="subcategory" onchange="checks(this)" onkeyup="checks(this)">
Now find the Line temp.options[0].selected=true and add this directaly below
createCookie("selected_option_1", x, 0);
if(x==0){
eraseCookie("selected_option_2");
}
then add these two new function say at the bottom of your script block
// checks if the Second Select has changed
function checks(oWhich){
createCookie("selected_option_2", oWhich.selectedIndex, 0);
}
// repopulate the options base on selection thats saved in the cookies
onload = function(){
if(readCookie("selected_option_1") != null) {
redirect(document.doublecombo.example.options.selectedIndex = readCookie("selected_option_1"));
if(readCookie("selected_option_2") != null) {
document.doublecombo.subcat.options.selectedIndex = readCookie("selected_option_2");
}
}
}
Finaly for these functions/scrip to work you will need
// The cookie script im using for the functions is located below include this and you chould ok. http://www.quirksmode.org/js/cookies.html#script
Now once the form has been submitted you GET the selected values as usual, and the REPOPULATE the menu, once you done with the cookie you could remove them.
If it's jQuery you are using you can try a short PHP tag on the page like this:
jQuery('#MyDropDown').val('<?php echo $_SESSION['MyStoredValue']; ?>');
If you are not using jQuery but straight JavaScript this would have the same effect:
document.getElementById("MyDropDown").value = '<?php echo $_SESSION['MyStoredValue']; ?>'

Categories