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!
Related
dropmenu is <select name="dropbox"> with 3 options - admin, activate, delete. The below snippet of code shows if the activate <option> is selected and submitted by the submit button then echo etc. I have a <select name="dropbox"> on every row for each user. My code only works if i change the last drop box.
if(isset($_POST['submit']))
{
if(isset($_POST['dropmenu']) && $_POST['dropmenu'] == 'activate')
{
echo 'is activated';
}
else{
echo 'fail';
}
}
Is there a way i can use foreach drop box with a value selected?
One of the possible ways is to connect the name of the select element with user id like
<select name="dropbox_[userId]">
In this case you simply know how to build an input name for checking it's value in $_POST table.
If you don't interate by users on submit code then you can use a regular expression to get an inforamtion abut user connected with element.
I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>
i have two text type forms(id,name) and another form dropbox type(school name)(select option type).
when user enters the id form, the remaining form (name) and the drop box(school name) needs to be filled based on the values in mysql.
filling form text type (name) is not a problem which i am able to do using json and jquery ,but i do not know how to auto select the dropbox.
any tutorials or code snippets suggestions are appreciated.
if your drop box is in xhtml, you can use the "selected" param.
with jquery, you could write semething like :
$("#optiontoSelect").attr("selected","selected");
More info in the jquery doc
I may have misunderstood the question. If you wish the focus to move from the input field to the select you would use .focus(). I would imagine you want to call focus on successful population of the select.
$('#select').focus();
or
$(this).focus();
jQuery Docs : focus()
This'll get you started:
<?php
$options = Array('red', 'green', 'blue');
$opt_from_db = 'green'; // for example
echo '<select name="fieldName">';
foreach ($options as $opt) {
$selected = ($opt_from_db == $opt) ? ' selected' : '';
echo "<option{$selected}>{$opt}</option>";
}
echo '</select>';
?>
The key is to write the selected attribute (in some form or another) into the programmatically-rendered HTML.
I am using CodeIgniter 1.7.1.Ok here is the scenario.When ever the form is submitted,i need to do two things
1) persist the value selected in dropdown.
2) using session->set_flashdata(),i need to set the custom database message.
Now as we know,we need to redirect before this flash data can be set.
This is the code which i have written.
if ($this->form_validation->run() == TRUE){
$this->session->set_flashdata(‘msg’, ‘Taha Hasan’);
redirect(current_url());
$this->ShowReceiveInventoryView();
}
Also i m using set_select in the dropdown view to persist the value.
<select name=“myselect”>
<option value=“one” <?php echo set_select(‘myselect’, ‘one’, TRUE); ?> >One</option>
<option value=“two” <?php echo set_select(‘myselect’, ‘two’); ?> >Two</option>
<option value=“three” <?php echo set_select(‘myselect’, ‘three’); ?> >Three</option>
</select>
Now here is the problem…The flash message appears BUT because i am redirecting to the current page,the drop down set_select value is lost !!! Default value appears in the selection :(..If i remove the redirect line in the code,the dropdown value is presisted but Flash data is not set !!!
Hope you guys have a solution to this problem…
set_select() only works when the $_POST array has content (as you've discovered), but your redirect is obviously a GET request.
The proper way to handle this is to perform your query within the Controller, passing the object that is being edited to your view. Within your view you then repopulate your form, or set default values, based on $_POST if it exists or based on the passed object.
Let's assume we are editing a product, which has the myselect (a horribly named field) property. We will use PHP's ternary operator to test if the value of the product's myselect parameter is equal to the current option - if so, we'll use set_selects()'s third parameter to set the default.
<option value="one" <?php echo set_select('myslect', 'one', ((!$product) || !$this->input->post('myselect') && $product->myselect == 'one' ? TRUE : FALSE); ?>One</option>
<option value="two" <?php echo set_select('myselect', 'two', (!$this->input->post('myselect') && $product->myselect == 'two' ? TRUE : FALSE); ?>Two</option>
here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));