I have created a PHP code to echo the following div
<div id="main_catsel">
<select id="maincat" >
<option value="1">none</option>
<option value="2">Computer</option>
<option value="4">Refrigerator</option>
<option value="13" selected="selected" >Grinder</option>
<option value="21">Bed</option>
</select>
</div>
I am using the option values and name as result from query . But now the default result still shown first is according to the id not according to selected="selected". Can any one sugsest a solution for this. Cant remove the id ,because its needed for insertion.
$maincat .='<div class="main_catsel">';
$sqlmaincat = $ilance->db->query("SELECT
cid FROM " . DB_PREFIX . "seller_profile
WHERE userid = '" . $uid . "'");
$row = $ilance->db->fetch_array($sqlmaincat);
$sqlcat = $ilance->db->query("SELECT
cid,title_spa
FROM " . DB_PREFIX . "categories
WHERE parentid = '0'
");
if ($ilance->db->num_rows($sqlcat) > 0)
{
$maincat .='<h2><select id="maincat">';
while ($rows = $ilance->db->fetch_array($sqlcat))
{
if($rows['cid']==$row['cid'])
{
$maincat .='<option selected="selected" value="'.$rows['cid'].'">'.$rows['title_spa'].'</option>';
}
else
{
$maincat .='<option value="'.$rows['cid'].'">'.$rows['title_spa'].'</option>';
}
}
$maincat .='</select></h2>';
}
$maincat .='</div>';
What browser are you using?
"On SGML and HTML" points out that some browsers only support the minimized form, i.e. selected rather than selected="selected".
Or maybe you previously selected something, and your browser is remembering your choice. Try holding Shift and clicking the Reload button, or press Ctrl+F5.
Or maybe the your browser is caching an older version of the page. Again Shift+Reload should help. Browser-specific details at Bypass your cache.
It seems that you just do like this
$("select#maincat").val("13");
Thats it. just try this and Let me know further.
Related
I am trying to accomplish two things with the code below. Firstly I want my select options to be populated form my database. Secondly I want the field in the form to have the stored value selected on page load (like in a profile for a member). The way I have implemented below works, kind of, but I have two problems. Firstly if you open the dropdown then the selected option appears twice (once at the top and once in its normal position). Secondly if it is a required field then the user has to open the dropdown and select it again, even though it is appearing in the field (horrible ux). If it is not a required field the form acts as if nothing is selected and I get a Undefined index error further down the line. I am very sure there is a better way to implement what I am trying to achieve that wont give me these problems... all help greatly appriciated.
<?php
$query6 = "SELECT catname FROM travisor_catagory";
$result6 = mysqli_query($conn, $query6) or die(mysqli_error($conn));
$queryread3 = "SELECT * FROM travisor_catagory WHERE id = $catagory";
$result3 = mysqli_query($conn, $queryread3) or die(mysqli_error($conn));
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
$cat = $row["catname"];
}
}
echo "<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<option disabled selected value> $cat </option>";
if (mysqli_num_rows($result6) > 0) {
while ($row2 = mysqli_fetch_assoc($result6)) {
$catagory2 = $row2["catname"];
echo "<option>$catagory2</option>";
}
}
echo "</select>"
?>
Don't mix things up so much.....
When you get into larger programs, you will get lost really quickly, so K.I.S.S.!!!
You can 'jump' in/out of HTML and back to PHP to echo the $options variable, then back to HTML to complete the select. (this is my description of it when I teach newbies - this concept of 'jump in/out' works for PHP, HTML, JS - well any languages that you can combine in one page... - it is worth grasping the concept!)
First, get the options you will need with ONE query (watch how we take care of the selected one as well) - this will make a 'packet' of data in the $options variable.
<?php
// declare some values that we'll use later
$options = '';
// gather the data for the options
$sql = "SELECT id, catname FROM travisor_catagory";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$selected = '';
if($category == $row['id']){
$selected = "selected";
}
$options .= '<option ' . $selected . ' value="' . $row["id"] . '">" . $row["catname"] . "</option>";
}
}
// now we will 'jump' out of PHP and back to HTML
?>
<!-- we are in HTML, so comments and language changed... -->
<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<!-- here we 'jump' out of HTML and into PHP to use the $options variable -->
<?php echo $options; // and back out of PHP to HTML... ?>
<!-- where we finish up our select and whatever other HTML things -->
</select>
</div>
That should take care of both your issues with what you had.....
BTW, it looks like you are using Bootstrap - if so, I HIGHLY recommend you check this out (changed my life about fighting with select boxes! :) Bootstrap Select
I have a form consisting of 11 elements (input and select tags). The form has form validation that prompts an error message next to field when a user inputs incorrect data. I want to maintain the correct data entered into the fields after the page is refreshed.
For instance, let's say that 10 fields where populated correctly and 1 field incorrectly. When the user presses the submit button, an error message is shown near the field. What I want to do is to keep the 10 correct values selected so the user does no have to start all over again.
For the input elements, this is working fine but for the select elements this is not working. Important is that I am populating the drop down list dynamically with PHP.
Is this possible to do in PHP since I cannot figure out how?
Below is an example of how I am generating a drop down list of a select element.
select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
echo '<option value="' . htmlspecialchars($row['description']) . '">'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As for the input elements I am achieving this using the below:
<input type="text" name="serial" value="<?php echo $serial;?>">
Try this:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
</select>
As outlined in the as duplicate linked question the selected attribute is to mark the option that has been submitted. The selected attribute addresses the issue to make the selected value visible.
Additionally your code can benefit from data-binding the select element to the (SQL) data in a modular way.
Let us not care for a moment on the retrieval of the data and just say they come from a Generator:
/**
* #param string $name of the select field
* #param string $value of the select field
* #param Generator $data to use as select field option values
* #return string HTML of the select element
*/
function select($name, $value, Generator $data) {
$buffer = sprintf('<select name="%s">', htmlspecialchars($name));
foreach ($data as $option) {
$buffer .= sprintf(
'<option%s>%s</option>',
$value === $option ? ' selected' : '',
htmlspecialchars($option)
);
}
$buffer .= "</select>\n";
return $buffer;
}
This little function returns the HMTL of a select element with the data from a Generator selecting an existing value (if part of the options).
Combining it with any generator, for example from a data-source, it can be easily put into your forms template script:
<form method="post">
<?= select('location', $_POST['location'] ?? 'default value',
datasource($connection, "SELECT description FROM location ORDER BY description ASC", "description")
) ?>
</form>
So if you've got 10 selects, this can be easily adopted. As the database connection as you know it is passed to the datasource function, it would be interesting to see what that function actually does. That function is even more simple:
/**
* #param mysqli $mysqli
* #param string $query
* #param string $field from query result to use as option values
* #return Generator
*/
function datasource(mysqli $mysqli, $query, $field) {
$result = $mysqli->query($query);
if ($result) foreach ($result as $row) {
yield $row[$field];
}
}
It queries the query on the database connection (it's a different way of writing as in your code, but it's the same $connection as in your example) and then iterates over the result (if there is a result). Then yielding each option value. That yield is a special form of returning from a function creating a Generator which is used in the select function for output, by having the Generator in the foreach loop there. Each yielding becomes one iteration of the Generator.
I hope this shows how you can benefit from dividing your code into functions. Values that change should be put into variables. This is easily done by creating functions and using parameters for these values. You sort of extend the language to your own special needs, like creating select elements.
Is this possible to do in PHP since I cannot figure out how?
Yes it is possible to keep the values selected, by using the selected attribute on the option elements.
For instance, the <option> tag below contains that attribute:
<option value="value2" selected>Value 2</option>
If you care about XHTML validation, use selected="selected" - refer to this answer for more information.
<option value="value2" selected="selected">Value 2</option>
From the examples section of the MDN documentation for <select>, the following HTML is listed:
<!-- The second value will be selected initially -->
<select name="select"> <!--Supplement an id here instead of using 'name'-->
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
Rendering a select list with PHP
To achieve this with the PHP code, the selected attribute needs to be conditionally added to the option.
First, before the while loop, store the selected location in a variable:
$selectedLocation = '';
if (isset($_POST['location'])) {
//Get selected value from values submitted with form
//use $_GET if form is submitted via GET
$selectedLocation = $_POST['location'];
}
Then in the while loop, set that selected attribute when the matching option is found (i.e. when $selectedLocation == $row['description']).
while($row = mysqli_fetch_assoc()){
$selected = ''; //default to empty string - not selected
if ($selectedLocation == $row['description']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['description']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
See a demosntration of this in this phpfiddle.
Edit and try:
<select name="location">
<?php
include("../includes/db_connect.php");
$sql_loc = "SELECT description FROM location ORDER BY description ASC";
$result_loc = mysqli_query($connection, $sql_loc);
if(mysqli_num_rows($result_loc) > 0){
while($row = mysqli_fetch_assoc($result_loc)){
$selected = "";
if ($row['description'] == $location) {
$selected = " selected";
}
echo '<option value="' . htmlspecialchars($row['description']) . '"' . $selected . '>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
I'm able to delete the entries which have a single word like 'Tomato' or 'Potato'.
Unable to delete entries with multiple words like 'pumpkin soup'.
Why is that?
Here's my PHP:
<?php
if(!empty($_POST['event_name_box']))
{
$del_event=$_POST['event_name_box'];
$sth = $conn->prepare("DELETE FROM event WHERE event_name=:del");
$sth->execute(array(':del'=>$del_event));
header( "Refresh: 0;" );
}
?>
And this is how I'm loading the values in drop down:
<select name="event_name_box" value="event_name_box" style="width:220px; padding-left:40px;font-size:18px;font-family:Roboto;">
<?php
$sth = $conn->prepare('Select event_name From event');
$sth->execute();
$data = $sth->fetchAll();
foreach ($data as $row ){
if($row['event_name']!="")
echo " <option id=\"EventName\" name=\"EventName\" value=".$row['event_name'].">".$row['event_name']."</option>";
}
?>
</select><br>
<input type="submit" name="submit" style="width:50%;padding:10px" value="Delete"</input>
The problem is in your HTML (specifically, the <option> tag). Your value isn't quoted, so the space is breaking the value sent in the POST. Change the echo on your option to something like this:
echo '<option value="' . $row['event_name'] . '">' . $row['event_name'] . '</option>';
(You also shouldn't need the name and id on your <option> tags.)
You are not quoting the value content in your <option tag, so it won't be interpreted correctly by the browser.
A simple trace in your PHP script should have made it obvious that it does not receive the proper content.
I have a mysql table with about 40 items in it. What I want to do is reference those 40 items in a form on my webpage with a drop down list.
Instead of writing it out all 40 items like the following to know if an item has been selected:
<!doctype html>
<html>
</head>
<body>
<select>
<option value="Health & Beauty"<?php if (isset($_POST['SiteType']) && ($_POST['SiteType'] == 'Health & Beauty')) echo ' selected="selected"'; ?>>Health & Beauty</option></select>
</body>
</html>
and so on 40 times...
I am wondering how I could do it instead by using an SQL statement like the following:
here is what I have so far.
$sql = "SELECT * FROM sitetypes";
$f = mysqli_query($dbc, $sql) or trigger_error("Query: $sql\n<br />Mysqli Error: " . mysqli_error($dbc));
while($row2 = mysqli_fetch_array($f, MYSQLI_ASSOC)){
echo '<option value="' . $row2['SiteTypeID'] . '">' . $row2['SiteType'] . '</option><\select>';
}
The code above produces a nice drop down list, but I don't know how to make the database know when an item is selected by a user. What code do I write to make that happen? Can I use the SQL statement option or do I have to write each item out like I wrote at the beginning of this post.
This might help you
Add Select Attribute to your Table of type varchar
alter table user add Selected varchar(255)
Give them all values to '0'
and in html page
<select name="sitename">
<option></option>
<!-- your options -->
</select>
and when form is submitted by your you simply use this
echo $_POST['sitename'];
Then use this query to database know user selected this field in usertable or where you want
Update user set selcted='$_POST["sitename"]' where userid='currectuserid'
I hope I understood you right
$sql = "SELECT * FROM sitetypes";
$f = mysqli_query($dbc, $sql) or trigger_error("Query: $sql\n<br />Mysqli Error: " .mysqli_error($dbc));
while($row2 = mysqli_fetch_array($f, MYSQLI_ASSOC)){
echo '<option value="' . $row2['SiteTypeID'] . ' '.($row2['SiteTypeName'] == $_POST['SiteType'] ? 'selected="selected"':'').'">' . $row2['SiteType'] . '</option><\select>';
}
I'm not sure if the syntax is right, but you get the idea.
Edit: as I Can Haz Cheeseburger suggested u need to get the name from the db (not id) or pass the ID through POST
I am trying to create a smart form which will automatically limit the options available of a second drop down box.
Background:
I am creating a ticketing system and I would like for the user to select a site from the "Site Selection" drop down and then the "User Selection" drop down will only contain users linked to the site selected on the first drop down, all information populated from MySQL.
Future:
I would then like to list all the services associated to that user with tick boxes under "Select Affected Services"
My js is pretty poor. So far I have been able to find some code by searching here that has allowed me to write the User's Computer ID into a text field. But I cannot figure out how to capture the output and query for the Computer Name (different table) and display that as a tick box option or to use the same method to limit the next lot of selection boxes. All code listed below I have not cleansed yet, alpha phase.
I realise that I could do this in steps using PHP only, but I am trying to pretty up my coding here and there.
Displaying Drop Downs:
<h3>Assign Site</h3>
<select id="site_add" name="site_add" style="width:217px; height:20px !important;">
<option value="-1"></option>';
$o = "SELECT * FROM company_sites WHERE company_id = " . $company_id . " ORDER BY sitename";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
echo '<option value="' . $r['id'] . '">' . $r['sitename'] . '</option>';
}
<h3>Assign User</h3>
<select id="comp_add" name="comp_add_1" style="width:217px; height:20px !important;">
<option value=""></option>';
$o = "SELECT * FROM company_staff WHERE company_id = " . $company_id . " ORDER BY id DESC";
$rs = mysql_query($o);
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++) {
$r = mysql_fetch_array($rs);
$user_computer_id = $r['computer_id'];
echo '<option value="' . $r['id'] . '">' . $r['firstname'] . ' ' . $r['lastname'] . '</option>';
}
Current JS to output selected user's computer ID into text field:
<script type="text/javascript">
window.onload=function() { attachBehaviors(); };
//
function attachBehaviors() {
document.getElementById(\'person\').onchange=function() {
loadUser(this.options[this.selectedIndex].value); // <-- check this, may be incorrect
}
}
function loadUser(optionvalue) {
// Always set a default
if (optionvalue==\'\') {
return;
}
opts = optionvalue.split(\':\');
var name = opts[0];
var email = opts[1];
document.getElementById(\'computer_id\').value=name;
}
</script>
<select name="person" id="person">
<option value=""></option>';
$result=mysql_query("SELECT * FROM company_staff");
while($row=mysql_fetch_array($result)) {
$submit_firstname = $row['firstname'];
$submit_lastname = $row['lastname'];
$submit_staff_id = $row['id'];
$submit_computer_id = $row['computer_id'];
echo '<option value="' . $submit_staff_id . '">' . $submit_firstname . ' ' . $submit_lastname . '</option>\n';
}
echo '
</select>
<input type="text" id="computer_id" name="name" placeholder="name" />
';
Any recommendations on how to achieve this would be greatly appreciated!
Thanks in advance!
You need AJAX, it's a combination of PHP and JS. ( javascript request data from the server, php processes the request, returns data ).
You would need to practice AJAX a bit to understand how to make this select box.
This is process in theory:
You output your first select box with PHP.
Make an onchange event handler for it that would call a server for information.
..options..
This updateNewDropDown function will take the value form a server response you selected and fetch the new data via PHP for the second select menu, and create the new select menu with the data AJAX response provided.
AJAX TUTORIALS:
http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/ajax/default.asp