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>
Related
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>
I'm having trouble populating a dropdown list from a database and then updating the selected item on a button click. What I'm trying to have is that when you pick Option B in the dropdown, it'll update that option on the click of a submit button.
I can get the dropdown box to populate fine, but when clicking the button it won't update correctly. I'm learning as I go, any pointers would be appreciated.
<form id='filter' name='filter' method='post' action=''>
<?php
$getIssuedVouchers2 = "SELECT * FROM vouchercodes WHERE status = 'Active'";
$issuedVouchersResult2 = mysql_query($getIssuedVouchers);
?>
<select>
<?php
while ($ivSelectRow = mysql_fetch_array($issuedVouchersResult2)) {
echo "<option name='updatestatus'>" . $ivSelectRow['vouchId'] . "</option>";
}
?>
</select>
<INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit" />
<?php
if(isset($_POST['Submit'])) { //if the submit button is clicked
$updatingQuery = "UPDATE vouchercodes SET status='Expired' WHERE vouchId = '".$ivSelectRow['vouchId']."' ";
mysql_query($updatingQuery) or die("Cannot update");//update or error
}
?>
</form>
PHP is a server side language. It runs once when you request the page, and after it is done it serves the page to you. It does not run until you do another page request, which PHP can't do because that's a client side action.
What you are looking for is Javascript and Ajax. They are client side languages. I'd recommend using Jquery for this, it's pretty easy to use once you get the hang of it. It makes it a lot less awful than standard javascript.
If you aren't wanting to avoid a page reload (submit -> handler -> page reload), I can cook up an answer for you for that. Maybe.
Update from your comment:
You want to set the "selected" attribute, which makes that option selected on page load, correct? e.g. pick the second item in the dropdown instead of the first.
You need to use the selected attribute on your option tag. That makes it selected.
Here's an example I use on one of my sites.
<select data-wavenum='<?=$i;?>' id="enemy<?=$i;?>" name="enemy<?=$i;?>" class="enemylist">
<option value="assaulttrooper" <?=($enemy == 'assaulttrooper') ? "selected" : ""?>>Assault Trooper</option>
This prints out something like:
<option value="assaulttrooper" selected>Assault Trooper</option>
In this case, $enemy is my item that makes me print selected out which makes that option be selected.
In your case, this is what it would be. It's kind of ugly. I think I fixed some of your code, but without the DB backend I can't test.
while ($ivSelectRow = mysql_fetch_array($issuedVouchersResult2)) {
$selected = false;
if (isset($_POST['Submit'])) {
$selected = ($_POST['vouchId'] == $ivSelectRow['vouchId']);
}
echo "<option name=".$ivSelectRow['vouchId']." ".($selected) ? "selected" : "".">" . $ivSelectRow['vouchId'] . "</option>";
}
Please be aware that I could change the option name or send a POST that would cause you to expire a value, or delete your entire table as your data is not sanitized.
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']; ?>'
I am filling DropDown dynamically using AJAX. The DropDown code looks like this:
<select class="element select medium" id="inDistrict" name="inDistrict" onclick="MakeRequest('divDistrict', 'inDistrict', 'SELECT * FROM districtmaster');" onchange="alert(document.getElementByID('inDistrict').value);">
<option value="Select" selected="Select">Select</option>
</select>
Another file that executes on AJAX request contains following code:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = $_GET['SqlQuery'];
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?= $row[0] ?>"><?= $row[1] ?></option>
<?php } ?>
</select>
Everything works fine and the DropDowns also get filled, except that I am not following how to pick the value of the Option. In the above code you can see that I am using row[0] as value and row[1] as the display item. I want to pick the row[0] value whenever a user selects any row[1] display item.
In the first code above, you can see that I added an onchange event and there is just an alert box. But it is not executing. How to pick the row[0] value and why onchange event is not firing?
onchange doesn't fire in response to DOM manipulation of the selected value. You can fire it manually with some simple javascript:
var inDistrict = document.getElementById('inDistrict');
if (inDistrict.onchange)
inDistrict.onchange();
If you're using jQuery, it's even easier:
$('#inDistrict').change();
Since it looks like you're replacing the entire dropdownlist with your ajax request, just throw some of that javascript in there to fire the change event when it's done populating, and you should be good to go.
Wrong case usage in your onchage event line:
document.getElementByID
Correct:
document.getElementById
Note that rather than using above; you can alert dropdown value like this too:
onchange="alert(this.value);"
Then for dropdown:
If you add [ ] to the names of elements, they become array eg:
<select name="myselect[]">
Now from php you can access each of its element like this:
(assuming that you post method in the form)
echo $_POST['myselect'][0]; // this prints first item value
echo $_POST['myselect'][1]; // this prints second item value
echo $_POST['myselect'][2]; // this prints third item value
//and so on...
I know how to 'remember' some form values whenever submitting the form to itself, in this case because of a picture upload function which requires the form to be submitted to itself. I simply want it so that if the user has filled out all fields and then uploads an image, the form doesn't get resetted (cleared).
I have solved this in regular fields and checkboxes like this:
<input type="text" name="headline" id="headline" value="<?php echo #$_POST['headline'];?>">
But how can I do this with drop lists? or radio buttons? There is no value option in a 'SELECT' list, even though I have tried writing in value anyways in the SELECT statement. Didn't work!
So, how can I set the SELECT (drop down lists) value with PHP (OR JAVASCRIPT) ?
If you need more input let me know, thanks!
For selects, you need to compare each option to your posted value, and handle it individually. Simply print out your options in a loop, and test each value against the value was was previously posted. If it maches, add selected to the attributes of that particular option.
$color = $_POST["colors"];
$colors = array("red","green","blue");
<select name="colors">
<?php foreach ($colors as $option) { ?>
<option<?php print ($option == $color) ? " selected" : ""; ?>>
<?php print $option; ?>
</option>
<?php } ?>
</select>
Actually, found out that it is possible to set the selectedIndex with javascript...
So I could put the selectedIndex in a hidden input before submitting the form, and then get that selectedIndex and set it with a javascript function... tricky but suits me better in this case...
document.getElementById("select").selectedIndex=nr;
Thanks though Jonathan!