Can´t find the mistake. I have three dropdown menus which are connected to a SQL server. When I load the page the first dropdown is already filled. After selecting a value from the first dropdown the page calls the function "reload(form)" from the script and in shows the new index in the second value. Till there it works fine, but when I select a value from the second dropdown in order to call the function "reload2(form)" it refreshs the whole page and the value selected from the first and second dropdown disappears and the dird dropdown doesn't show anything.
Here is the script code:
<script language=JavaScript>
function reload(form)
{
var val=document.form.cliente.options[form.cliente.options.selectedIndex].value;
self.location='indexmm.php?cliente=' + val ;
}
function reload2(form)
{
var val=document.form.cliente.options[form.cliente.options.selectedIndex].value;
var val2=document.form.equipos.options[form.equipos.options.selectedIndex].value;
self.location='indexmm.php?cliente=' + val + '&equipos=' + val2 ;
}
</script>
And here is my php code:
<form method="post" name="form" id="form" action="post.php">
<h1>Cliente:
<?php
echo "<select name='cliente' onchange=\"reload(this.form)\"><option value=''>Seleccione...</option>";
while($busq1 = mysql_fetch_array($consultacliente)) {
if($busq1['IdCln']==#$cliente){echo utf8_encode("<option selected value='$busq[IdCln]'>$busq1[Cliente]</option>"."<BR>");}
else{echo utf8_encode("<option value='$busq1[IdCln]'>$busq1[Cliente]</option>");}
}
echo "</select>"
?>
</h1>
<h1>Equipos:</br></h1>
<?php
echo "<select name='equipos' size='5' style='width:400px' onchange=\"reload2(this.form)\">";
while($busq3 = mysql_fetch_array($consultaequipos)) {
if($busq3['IdGn']==#$refaccioness){
echo utf8_encode("<option selected value='$busq3[IdGn]'>$busq3[Generador]</option>"."<BR>");}
else{echo utf8_encode("<option value='$busq3[IdGn]'>$busq3[Generador]</option>");}
}
echo "</select>"
?>
</h1>
<h1>Refacciones:</br></h1>
<?php
echo "<select name='refacciones' size='20' style='width:400px'>";
while($busq4 = mysql_fetch_array($consultarefac)) {
echo utf8_encode("<option value='$busq4[Descripcion]'>$busq2[Descripcion]</option>");
}
echo "</select>"
?>
The variables $consultarefac, $consultacliente, $consultaequipos are the SQL query.
Any suggestion?
I would recommend NOT reloading the page every time someone changes a dropdown. I would recommend only updating the dropdowns below the current one using AJAX.
Simple AJAX call would be to replace a div surrounding the following dropdown(s) with a snippet of html. The first select will replace the contents of div 'second' (which will include clearing the third dropdown. The second select will replace the contents of div 'third'.
The pages you grab with ajax will return the html snippet for only the appropriate section. The replace functions will use ajax against the appropriate pages to replace the contents of the appropriate div.
<div id="first">
<select name=first onchange="replace1()"></select>
<div id="second">
<select name=second onchange="replace2()"></select>
<div id="third">
<select name=third></select>
</div>
</div>
</div>
Related
Bellow I have two drop-down menus. One fetches the list of "Coalitions" and the other the list of "candidates" from the database. What I'm trying to do is to list the candidates in the second drop-down menu, based on the coalition selected in the first. Basically list/set the candidates that are in the same coalition in the second drop-down menu. The problem is that I'm unable to first get the selected item from the "coalition" menu and second use that value to set the second.
here is my code:
<form action ="includes/admin.users.inc.php" method="POST">
<div style = "display: inline-block;">
<!-- the coalitions -->
<select class="form-control" id = "coalition_id" name ="coalition_select" method="POST">
<option value="" selected disabled>Coalitions</option>
<?php
include_once 'includes/dbh.inc.php';
$sql_coalition = mysqli_query($conn, "SELECT coalition FROM candidates");
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"\">" . $row['coalition'] . "</option>";
}
global $coalition_select;
echo $coalition_select = $_POST['coalition_select'];
?>
</select>
</div>
<div style = "display: inline-block;">
<!-- the users -->
<select class="form-control">
<option value="" selected disabled>Candidates</option>
<?php
include_once 'includes/dbh.inc.php';
$sql = mysqli_query($conn, "SELECT username FROM candidates WHERE coalition = '$coalition_select'");
while ($row = $sql->fetch_assoc()) {
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
</div>
</form>
I looked at few examples dealing with a similar situation with no success. The two menus function just fine separately so the issue is not with the connection. Please note that I wish for this action to takes place without any button being pressed.
Thanks
As php is server side code, you can't get the 1st dropdown's selected value in php part (for the 2nd dropdown).
To fill the 2nd dropdown based on 1st dropdown's selection, you need to use ajax.
Do a ajax call on "change" event of 1st dropdown ie Coalitions and ajax url should return you the list of candidates based on ajax parameter ( Coalitions selected value). Once you get the ajax response them you can fill those values in "Candidates" dropdown using JS/Jquery.
Here are the sample code which should fulfill your requirement:
$( "#coalition_id" ).change(function() {
var selected_id = $(this).val();
// path of the file which should return list of candidates (JSON
format ) for "coalition" value passed to this url via GET method
var url = "path/to/candidates_file.php?coalition=" + selected_id;
// ajax call
$.get(, function(json, status){
$('#candidatesselect').empty();
// loop through each value & fill the candidates dropdown
$.each(json, function(i, item) {
$('#candidatesselect').append(
$('', {
value: item.owner,
text: item.username
}, ''));
});
});
});
I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or would I need to delve into the AJAX world? If that's the case, how would I use AJAX and PHP together in the scope of this project?
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option value=$name></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option>$name</option>";
}
echo "</select>";
echo "</fieldset>";
?>
</form>
</div>
This is definitely an AJAX situation. I'm not sure if you're using JQuery on this page, but that would help you a lot.
It would look something like this:
$("#selectCust").change(function(){
var selected = $("#selectCust").val();
$.ajax({
url: "backEnd.php",
data: {
'selected': selected
},
success: function(data) {
$( this ).addClass( "done" );
}
});
});
The database stuff would occur in backEnd.php.
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>
What I want to be able to do is to:
--- have an "on change" on drop list (containing the table data "titles")
--- this on change runs the javascript function
--- the javascript populates a text area with a "message" column of data in the same table as the corresponding title that is being selected in the drop list.
<li><label for="frm_precan">Canned Response</label>
<span class="input">
<select id="frm_precan" name="precan" onchange="updateText();">
<option value="">--Please Select--</option>
<?php foreach($precan_list as $precan) : ?>
<option value="<?=$precan['id'];?>"><?=$precan['name'];?></option>
<?php endforeach; ?>
</select>
</span>
</li>
</ul>
<textarea style="width: 100%; margin: 0; padding: 0; border-width: 1; font-family: courier;" name="message" rows="10" id="text_area"></textarea>
<script type="text/javascript">
function updateText()
{
var value = $("#frm_precan option:selected").text();
$('#text_area').val(value);;
}
</script>
This is the code, and it currently can put the selected title in the text area. However, I need to get data from database according to selected index of the dropdown and fill the textbox with it. How can I do this?
You cannot fill the textbox with pure JavaScript. JavaScript works client-side and you need to access the database on a change of selection in the dropdown menu. For that, you need to recall the same page on a dropdown selection change. After you get the data from database, it's easy to create a textbox with the data with "echo" command.
<?
if (isset($_POST['my_selection'])) {
$result=mysql_query("SELECT * FROM `table` WHERE `column`='".mysql_real_escape_string($_POST['my_selection'])."'");
$row=mysql_fetch_array($result);
echo "<input type='text' value='".$row['column']."'>";
echo "<input type='text' value='".$row['column1']."'>";
}
?>
<select name='my_selection'>
Your existing select box here...
EDIT: My main code no longer works, should this function work?
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script>
var second_choice = $('#second-choice').val();
$("#first-choice").change(function() {
$("$second-choice").load("findModel.php?choice=" + $("#first-choice").val());
});
</script>
Here is the associated PHP File:
<?php
include 'dbc.php';
$choice = mysql_real_escape_string($_GET['choice']);
$query="SELECT * FROM `cars` WHERE `DVLAMake`='$choice'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<option>" . $row{'DVLAModel'} . "</option>";
}
?>
The database connection works.
#
On load a PHP file populates my first dropdown:
<form name="indexSearch" action="searchResults.php" method="POST">
<select id="first-choice">
<option selected value="base">Please Select</option>
<option value="VAUXHALL">VAUXHALL</option>
<?php
$sql="SELECT DISTINCT `DVLAMake` FROM `cars`";
$result = mysql_query($sql);
while ($data=mysql_fetch_assoc($result))
{
echo "<option value =\"{$data[DVLAMake]}\" >{$data[DVLAMake]}</option>\n";
}
?>
</select>
<select id="second-choice">
<option>Please choose from above</option>
</select>
<br />
<input type="submit" style="font-size:14px; padding:3;"value="Submit" size="20" />
</form>
That works, and then on choosing the value it calls a function which then fills the second with options which I can choose from. However when I post the form, it doesn't take the second dropdown selected value through it's just empty but it does take the first dropdown value selected value.
Any reason why?
The problem is that the second select tag does not have name attribute. if it lies in the form you will get the request via post only if the attribute has name. if you are using jquery you can simply fetch value by id then post it via ajax. select like this in jquery.
var second_choice = $('#second-choice').val();
How are you changing the selected value? Using e.g. ajax? And how are you sending your data? Using ajax or simple POST with page reload?
If you're changing something using ajax your data need to be send by ajax. Because without it you will don't send your data generated by JS but this generated by your PHP script.
You wrote
$("$second-choice").load("findModel.php?choice=" + $("#first-choice").val());
instead of:
$("#second-choice").load("findModel.php?choice=" + $("#first-choice").val());
$ -> #