I want to do this function in php. i have two fields, one is text box and an
other one is drop down list. Drop down list contains values from sql. When one of the value is selected from the drop down list i want the text box to be filled according to the option which is selected.
Following is the drop down list code,
<td>Test Group ID</td>
<td><select id="testgroupid" name="testgroupid" style="column-width:35">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH)){
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select></td>
According to the id,I want textbox to be filled, How can i do this ? Pls help friends.
<tr>
<td>Test Group Name</td>
<td><input type="text" name="testgroupname" id="zipsearch" value="<?php echo $testgroupname; ?> "></td>
</tr>
If you want your textbox to be filled immediately after the dropdown selection changes, the simplest way is to use javascript:
<td><select id="testgroupid" name="testgroupid" style="column-width:35"
onchange='document.getElementsByName("testgroupname")[0].value =
document.getElementById("testgroupid").options[e.selectedIndex].value;'>
You need JavaScript for that. Use jQuery (or your favorite library) and bind an event listener to the combobox.
Example with jQuery:
$("#myCombo").change(function(e){
$("myTextField").val( $("#myCombo").val() );
});
I have one suggestion which involves jQuery. I do not know if you are using this library, but I am posting it anyway :)
<script type="text/javascript">
$(function() {
$("#testgroupid").change(function{
$("#zipsearch").text($(this option:selected).val();
});
});
</script>
On change event on the dropbown-box, this function fires, and sets the zipsearch-input accordingly.
I am not sure where $testgroupname comes from but I take it you would like to get that value upon selection in the dropdown. If you don´t have the value available on the client you have to retrieve it from the server somehow.
You can´t use PHP to fill the text box since you do not send your posts when an options is selected in the dropdown. There are many alternatives on how to solve this. I would personally use Ajax to fill the textbox without posting to server.
Good place to start:
http://buffernow.com/2012/08/cascading-dropdown-ajax/
html
<select id="testgroupid" name="testgroupid"
style="column-width:35" onChange=filltext();>
javascript
function filltext()
{
var e = document.getElementById("testgroupid");
var group = e.options[e.selectedIndex].text;
document.getElementById("zipsearch").value= group ;
}
your php code is wrong here
<option value="<?=$res['Id'];?>"><?=`$res['Id']`;?></option>
change to
<option value="<?=$res['Id'];?>"><?=$res['GROUP_NAME'];?></option>
Try like this
<script>
function selecteditem(selectedval)
{
jQuery.post("<?php echo JURI::root().'test.php'?>", { id: selectedval },
function(data) {
jQuery('.zipsearch').val(data);
});
}
</script>
//test.php on the root
<?php
$val=$_POST['id'];
//do what you want with $val
//and say final output is in variable $result than echo it
echo $result;
?>
<!--html code here-->
<select id="testgroupid" name="testgroupid" style="column-width:35" onclick="selecteditem(this.value);">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH))
{
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select>
<input type="text" name="testgroupname" id="zipsearch" class="zipsearch" value="<?php echo $testgroupname; ?> ">
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '</form>';
?>
<script language="JavaScript">
function send_input1(){
document.send1.input4.value = document.send3.populate.value;
}
</script>
<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>
Related
I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.
I need to get the list of diagnosed disease of the patient by choosing his name in the combo box, how can I do that? This is my code.
<select name="pname" class="textfields" id="model" style="width:180px;" onchange="getVal1();">
<option id="0" >--Select Patient Name--</option>
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pnum = $_GET['pnum'];
$query = mysqli_query($con, "SELECT * FROM tblnpatient");
while($row = mysqli_fetch_array($query)){
$pnum = $row['pnum'];
$pname = $row['pname'];
$addr = $row['addr'];
$complaints = $row['complaints'];
?>
<option id="<?php echo $pnum; ?>" data-pnum="<?php echo $pnum; ?>" data-addr="<?php echo $addr; ?>" data-complaints="<?php echo $complaints; ?>" value="<?php echo $pname; ?>"><?php echo $pname; ?></option>
<?php } ?>
This is my code for filtering the table: And i having a trouble in this code because nothings appear in the table when i select the pname
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pname = $_GET['pname'];
$result = mysqli_query($con,"SELECT * FROM tbldiagnosis WHERE pname='$pname'");
while($row = mysqli_fetch_array($result)) {
echo '<tr class="record">';
echo '<td>'.$row['diagnosis'].'</td>';
}
?>
This can be easily done using ajax. On change of the select, you can trigger a jQuery call to submit the selected value of the box to your PHP page, which has the MySQL to filter the table. The returned result will then be displayed on the page in the designated area.
Main Page:
<select name="pname">
<option value="pname-value">pname-value</option>
</select><br>
<div id="query_results"></div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="pname"]).on('change',function() {
var curPname=$(this).val();
$.ajax({
type:'GET',
url:'urltotable.php?pname='+curPname,
success:function(data) {
$("div#query_results").html(data);
}
});
});
});
</script>
This is a simplified ajax call that will grab the value from the select box named "pname" and it will send that value to the "url" variable in the ajax call via "GET". This page can then take that variable via GET and use it to get the query results. Upon successful completion, it will display the results inside the div we added with the ID of "query_results".
You can easily customize the select to use your current PHP as listed above, also.
Now for the "urltotable.php" as we specified above, you can use the table query you have above, but just be sure to add the GET line to it so that your pname variable is accessible to the script:
$pname=$_GET["pname"];
For more information about Ajax for full features list, click here to read about Ajax in the jQuery documentation.
I'm trying to create an "editable" drop down list. I have a drop down list populated from a table "city" in my db, it works perfect but now I want user to be able to add a new value to the list if it doesn't exist there (and I want to save this value, so next time it appears in the drop down list).
Any ideas?
Thank you
<select name="city">
<?php
// connecting to DB
$con= mysqli_connect('localhost','root','1234','e-sage');
// enable hebrew input
mysqli_set_charset($con,'utf8');
// read the city table from DB
$sql = mysqli_query($con,"SELECT CityName FROM city");
while ($row = mysqli_fetch_array($sql)){
// creating temporary variable for each row
$city1=$row["CityName"];
//assigning a value to each option in dropdown list
echo "<option value=\"$city1\"> $city1 </option>";
}
?>
</select>
You can provide a 'other' selection in the dropdown. If user selects that then display a new textbox from which you can insert in the database.
Then try this:
Lets agree that you already got all the cities in array OK?
<select name="city">
<?PHP
foreach($cities as $city)
{
echo '<option value="'.$city.'">'.$city.'</option>';
}
?>
</select>
<form method="post">
<label for="new_city">New city</label>
<input id="new_city" name="new_city" placeholder="Enter new city name" />
<input type="button" id="addCity" value="Insert city" />
</form>
<script>
$(document).on('click','#addCity',function()
{
var new_city=$("#new_city").val();
var e=0;
$("[name='city'] option").each(function(i,item)
{
var check_city=$(item).val();
if(check_city==new_city)
{
e++;
}
else
{
}
});
if(e>0)
{
alert('The same');
}
else
{
/*Submit the form*/
alert('This city is fresh and new');
}
});
</script>
So the script is checking if the value is already assigned to option. If not - allows to submit the form.
Check this one: http://jsfiddle.net/n47N2/1/
use datalist tag
link to w3School tutorial
I have a database named Data which has a table in which their are different names of products their id and prices, i want to make a web page using php so that i can edit,add and save the items from the web page to the DB and search the names accordingly.
<html>
<head>
<title>Products store</title>
</head>
<body>
<p style="font-size:20px" align="center"> <b>Product Database Editor</b> </p>
<p>
<form method="post">
Enter Product Name: <input type="text" name="pname" id="pname" size="70">
<input type="submit">
</p>
<form method="post">
<select id="opt" name="opt">
<?php
$pname = $_REQUEST['pname'];
// $pname= mysql_real_escape_string($_POST['pname']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Dataentry", $con);
$result = mysql_query("SELECT * FROM products where name like '%$pname%'");
$result_rows = mysql_num_rows($result);
if($pname==NULL)
{
echo "Please enter a product name!";
}
else if($result_rows==0)
{
echo "Product Name does not exist!";
}
else
{
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
echo "<option value='$name_selected'>$name</option>";
//echo ("<option value = '" . $row['name'] . "'>" . $row['id'] . "</option>");
echo $name_selected;
echo "<br />";
}
}
mysql_close($con);
?>
</select>
</form>
</body>
</html>
when i run this code i get the names list in the dropdown but after i select any name, nothing happens, how should i modify my code so that i can select any name from the dropdown and then be able to fetch the price of that particular name to edit it.
please help, coding will be much helpful.
Suppose you have a question like this in your dropdown menu.
Q - How many colors does the US flag has?
Now, from what I understand you want your choice from the drop down menu to appear instantly..
Well, here is a simple select form.
<form method="post">
<select id="opt" name="opt">
<option value="four">four</option>
<option value="five">five</option>
<option value="two">two</option>
<option value="million">million</option>
</select>
And, the JS code:
$(document).ready(function() {
$("#opt").change(function() {
alert($(this).val());
});
});
Now, click her a DEMO with jsFiddle to show you, how it works.
You can copy/paste the codes and include them in your site, this is a simple code, but you if you small knowledge of Javascript you can manipulate the data the way you need it to appear. .
To get a value of an input (this case, from a dropdown) on the fly, you need to use client-side scripting language javascript (or jquery) and use ajax to sent it to server-side, where the code is in PHP.
I would like some help with my code. I've already searched answered questions on this site but haven't found anything that works unfortunately. I'm doing a website where you can write, save, delete and update notes. Now I'm trying to fix an update button were you can change a posted note using its unique ID. The update button is on a separate page from the notes, and you choose the ID of posted notes using using a drop-down menu showing the existing IDs in my database table. You choose it, write a new note and then click update.
This is my current code:
<li id="id_number"><label>ID number: <select name="id_number">
<option value =" ">Select number</option>
<?php $query = "SELECT * FROM notes";
$result2 = mysql_query($query);
while ($row = mysql_fetch_array($result2)) {
$id = $row ['id'];
$select = "";
if ($id == $idID2) {
$select = "selected" ;
}
?><option <?php print $select ?> value="<?php print $id; ?>"><?php print "$id";
?></option><?php
}
?>
</select>
</label></li>
<li id="note">New note:</li>
<li id="note"> <textarea rows="10" cols="30" name="note" value="<?php print $note;?>"/></textarea></li>
<li id="send"><input type="submit" name="submit" value="Update!"/></li>
</ul>
</form>
<?php
$id= $_POST ['id'];
$subject= $_POST ['subject'];
$note= $_POST ['note'];
?>
<?php
if (isset($_POST['submit'])) { //validates the data
$error="0";
if ( $note == "" ) {
$error++;
$wrong .= "<p> You forgot to write a new note.</p>";
}
if ($error > 0) {
print "<p><strong>You have made these errors:</strong></p>";
?>
<?php print $wrong; ?>
<?php
}
//if no errors
else {
$note = mysql_real_escape_string($note);
$note = htmlspecialchars($note);
$id = mysql_real_escape_string($id);
$id = htmlspecialchars($id);
$date = date("j/n, Y, H:i");
$query = ("UPDATE notes SET note='$note' WHERE id='$id'");
$result = mysql_query($query) or die (mysql_error());
if ($result) {
print "<p>Note updated!</p>";
}
}
}
?>
When choosing an existing ID and change the note and clicking update it says "Note updated" but the note in the database remains the same.
What am i doing wrong?
$id = $_POST['id']
should be
$id = $_POST['id_number']
As far as I can tell, you aren't referring to any input with name "id".
Instead of answering "what am I doing wrong?" I'm going to answer "How can I do this right?"
Your interface is set up in a fashion that is not intuitive. The dropdown should contain information about the notes (the ID is sufficient here), and when the user selects a note from the dropdown, your text input should be populated with what's already there. If no note ID is selected from the dropdown and the user clicks "update", the system should insert a new note record (if the text area has content).
So, how do we do this? First let's set up our form:
<form action="" method="post">
<select id="noteIds" name="noteId">
<option value=''>Select a Note</option>
<option value='1'>1</option>
<option value='2'>2</option>
.
.
.
</select> <br />
<textarea name="noteContents" id="noteContents"></textarea><br />
<input type="submit" value="Update" />
</form>
Now that we have our form set up we can control the behavior of the elements using jQuery:
<script language="javascript" type="text/javascript">
$("#noteIds").on('change', function() {
$.post("getNoteInfo.php", {
noteId: $(this).val()
}, function(data) {
$("#noteContents").html(data);
}
);
});
</script>
The above code will set the output of geNoteInfo.php to the contents of your textarea.
Next let's work on getNoteInfo.php (in pseudo-code).
<?php
$noteId = $_POST['noteId'];
$noteText = // retrieve note text from database where note ID = $noteId
echo $noteText;
Now, when the user clicks Update, check to see that an ID is selected. If the ID was selected, update that row. If no ID has been selected, insert a new row IF there is text in the textarea.
NOTE: You should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article.