List menu -- How to execute statement when item is selected? - php

In Dreamweaver I have a list box or menu/list.
I am dynamically adding data from an array into it, so when the page loads, I have a list-box with names in.
This is how it looks
<?php
echo "<select name="."username"."id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
Now how do I go about making the listbox executesomething when the user selects something in it?
Because I have three other textboxes, and when the user selects a name in the list box, I want to put that name he selected into a variable (also don't know how I'm going to do that with a list box) and then search through my database and insert some of the data of that person in the textboxes.
So all i need to know is:
How to create that on event click event and
How to put that selected value then in a variable (inside the event)

You can easily execute a javascript function by using something like this:
<select name=".$username."id=".$username." onchange='yourfunction()' >

The following php code generated a select field with a dynamic number of options.
<?php
$user_array = Array("Smith", "John", "Bob", "Jake");
echo "<select name="."username"." id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
The following JavaScript handles change events on the select element.
$(document).ready(function() {
var username = $('#username');
var selectedValue = null;
username.change(function(){
alert(username.val());
selectedValue = username.val();
});
});

Related

Display values from php while loop to dropdown in jquery

When a hyperlink 'Add More' is clicked, a dropdown list is added using jquery. I want the values in this dropdown to be generated from the mysql database using php.
I tried many ways,but i not able to get the values from php to jquery.. The values retrieved from mysql database using while loop should be displayed in the dropdown using jquery. Thanks
The values in $val should be displayed in dropdown options
Here is the sample
php code retrieving values from database
<?php
$aquery = "SELECT * from filter";
$aresult =$base->execute_query($aquery);
while($row=mysql_fetch_array($aresult))
{
$val=$row[1];
}
?>
jquery where $val values should be added in dropdown
<script type="text/javascript">
jQuery(document).ready(function($){
$('.my-form .add-box').click(function(){
var box_html = $('<select><option><?php echo $val; ?></option>');
$('.add-box:last').before(box_html);
return false;
});
});
</script>
Please help me.Thanks
If you want this on button click as your code then try this solution:
var box_html = '<select><?php foreach ($val as $value) {
echo "<option>$value</option>" ;
}?>';
The PHP Script is actually over-writing on your $val.
Perhaps you can do the following:
<?php
$val = "";
while($row = mysql_fetch_array($aresult)) {
$val .= "<option value=". $row[1] .">". $row[1] ."</option>";
}
?>
and your JavaScript code should suffice in this case, just remove the option tags before the php script.
Hope this helps.
var box_html = $('<select><?php echo $val; ?></select>');
php will build you an array
you need to convert it to java object json_encode
try var abc=
also when your printing it you need to run a loop through the object after creating the select section
see each() jquery

Need PHP dropdown with result shown in text box

I am using php and getting data from mysql. I would like to have a dropdown of countries and then when the country is selected then the prefix must be the result either in a text box on the same line or just below the dropdown box.
so far my code gives me the prefix concatenated with prefix eg
Zimbabwe-263
here is the code
<?php
include 'config.php';
$query="SELECT countryname, countryprefix FROM cc_country";
$result = mysql_query($query);
$options="";
echo "<select name='processor' value=''>
<option>Select A Country</option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value='".$nt['countryprefix']."'>".$nt['countryname']."-".$nt['countryprefix']."</option>";
}
If you want the selected value to display in textbox you can use jquery for that.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<sctipt>
$('select').change(function(){
var value=$(this).val();
$('#text').val(value);
});
</script>
Create a textbox with id text for this
You will need to fire another query that will fetch the country prefix on selection of the country.That is pass the value of your select box to he sql query.You can do this using jquery or javascript by giving an id to the select box you are using .
var countryname = $('#yourId').val();
then do a ajax or jquery post to a PHP file which will have the blow query.
For example:
$query="SELECT countryprefix FROM cc_country where countryname='your post value";
then below your while loop add a text field which will display the value returned by your above query
$('select').change(function(){
var value = $(this).val();
$('.textbox').val(value); // html <input type="text" class="textbox">
});

using the selected item of drop down menu on same page using php

i have created the drop down menu using php and i want to use the selected value of menu on url of the current page. How can i do this without redirecting to the next page. the code for creating dropdown menu is:
echo '<select name="Company">';
if($data['count']>0){
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select>";
Hum? Dont know what you exactly want. You want to create a dropdown menu and use the selected value on the current php page?
That wont work. Ill show you how it works:
PHP renders page -> gives it to you.
When you see the page, the php-script is already done. So you have to call your page again and give it the value via $_POST ...
echo <form action="page.php" method="post">
echo '<select name="Company">';
if($data['count']>0) {
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select></form>";
... or $_GET (this only works in combination with JS!) ...
echo "<a href='page.php?company=companyname'>Im a link!</a>"
You need to get drop down value using javascript or JQuery
In Javascript:
<script type="text/javascript">
var myselect=document.getElementById("Company")
for (var i=0; i<myselect.options.length; i++){
if (myselect.options[i].selected==true){
alert("Selected Option's index: "+i)
break
}
}
</script>
In JQuery
$('select[name=Company]').val()
It's not entirely clear how you want to use this value, but you can refer to it on the same page using javascript. Consider the code below, which will update the line "Your company is:" whenever a new option is selected from the dropdown box.
<script type="application/javascript">
function update_box() {
selected_value = document.getElementById('company_dropdown').value;
document.getElementById('your_company').innerText = selected_value;
}
</script>
<form action="page.php" method="post" id="my_form" name="my_form" onchange="update_box()">
<select name="company_dropdown" id="company_dropdown">
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
</select>
</form>
Your company is: <span id="your_company" name="your_company"></span>
If I am getting it right, you want to use the selected value from dropdown on the same page url via querystring.
You can do that like following:-
echo '<select name="Company" onchange="location.href = location.href+'?var=' + this.value">';
if($data['count']>0){
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select>";
When you will change the value in dropdown, current page will refresh with the selected option value in querystring. You can use the querystring value as following:-
<?php echo isset($_GET['var']) ? $_GET['var'] : ''; ?>
You can also do it via use of hash value without refreshing the page
When ever you change the dropdown on the onchange event you can write the code
onchange="window.location.hash(this.value);"
it will set a hash value in the url and then you can write a function which will detect the change in the hash value as the page is not refreshing you need to track the change in the hash value and then you can show the selected menu on the basis oh the hash value.
use this to detect the change in the hash value
$(document).ready(function() {
$(window).bind('hashchange', function(e) {
var hashStr = window.location.hash;
hashStr = hashStr.substring(1, hashStr.length);
hashArray = hashStr.split('&');
// here you will get the array of all the parameters you passed in the array
});
});

One drop down box helps populates the other

I have a form to insert data into a MySQL table that uses two drop down menus. The first is a list of parks and the second a list of rides. The second drop down box should only display items linked to the first by the column 'park_id'. I need a simple way for the second box to populate based on the first's selection.
This is the form so far:
<tr><td>Select Park:</td>
<td><select name="park_id">
<option value="">Select Park</option>
<?php foreach ($res as $row) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row['park_id'], $row['name'] );
} ?>
</select></td></tr>
<tr><td>Select Ride:</td>
<td><select name="ride_id">
<option value="">Select Ride</option>
<?php foreach ($res2 as $row2) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row2['ride_id'], $row2['name'] );
} ?>
</select></td></tr>
So somehow a query needs to run after selecting a park and use '$park_id = $row[park_id]' to help generate the results for the 'Select Ride' dropdown.
This is the query I need to use for the second drop down:
$qry2 = "SELECT ride_id, name FROM tpf_rides WHERE park_id = $park_id ORDER BY name ASC";
Can anyone talk me through this? Also my skill are very limited so a relatively simple solution would be great.
Thanksark
For this you will have to get into AJAX, and I highly recommend using jQuery's implementation. You will also need to get a good grip on JSON string coding and decoding.
The basic Idea of your code will be like so:
// listen for user to change the <select> item
$('select#park').on('change', function(){
$.ajax({
url: 'getrides.php' // send a park id to this script
,cache: false // do not cache results in browser
,type: 'POST' // send POST to getrides.php
,data: {'park_id': $('select#park').val()} // getrides.php will receive $_POST['park_id']
,dataType: 'json' // this AJAX call expects a JSON string as a return value
,success: function(data){ // the data variable will be converted to an array from JSON
// check out all your data
console.log(data);
// loop through your array
$.each(data, function(index, info){
// see your array indexes
console.log(index);
// see data in each array item
console.log(info);
});
}
});
UPDATE
You can also load all of the parks and rides into a Javascript array and based on what the user chooses from the dropdown then populate the second dropdown with those array members.
<script>
var rides = new Array();
rides['park1'].push('ride1');
rides['park1'].push('ride2');
rides['park1'].push('ride3');
rides['park1'].push('ride4');
rides['park1'].push('ride5');
rides['park2'].push('ride1');
rides['park2'].push('ride2');
rides['park2'].push('ride3');
rides['park2'].push('ride4');
rides['park2'].push('ride5');
// listen for user to change the <select> item
$('select#park').on('change', function(){
// clear current DD options
$('select#rides').html();
// loop through array of available rides for selected park
$.each(rides[''+$(this).val()+''], function(index, value){
// dynamically create the proper DD options
$('select#rides').append('<option>'+value+'</option>');
});
});
</script>
you have to write another file that uses the id of the first selected from the bikes list value to load the options of the second select tag the rides list
then make an empty div on the first file that will be loaded with the result of the second file which is the list of rides
$(function() {
$('#ID_of_the_park_selecttag').change(function() {
var value = $("#ID_of_the_park_selecttag").find('option:selected').text();
$("#ID_OF_THE_DIV").html("");
$("#ID_OF_THE_DIV").load('theOtherFile.php', {"bikename":value } );// value is the value of the select option from the first <select tag>
});});
then on the second file you can get the value of the bike selected as $_POST['bikename'] and do your query then fill the list
I had to do this recently myself. Here's what I did, feel free to use what makes sense to you. I tried what seemed like a simple way to myself.
<select name="department_list" id="department_list" onchange="$('#singleUser').load('yourextraphppage.php?nid='+this.value);">
<option value='none'>Select a department</option>
Then load your first select list with data and close the select tag... Add a blank div where you want the 2nd select. I used the value from the first select list for my parameter for the 2nd select list's query. (it was the foreign key in the 2nd table for the 2nd select list)
<div id="singleUser" class="singleUser">
</div>
Last, you need the additional PHP page that you called from the first select list. Here's a barebones version of my code.
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
I hope this helps. I'm rather busy so I can't go in detail explaining it at the moment. I'll check back later to see if you have any questions.
I was helping somebody a similar page a day or say ago:
2 dropdown selects and the list of options in the second dropdown changed according to the choice selected in the first.
The solution involved the use of <optgroup> elements within the <select> and jQuery (which is not all that easy for a beginner but at least you can copy the code.
See here for the question: jQuery - on page load select optgoup and children in second select by a default selected option in a parent select
And here to see the code in action here: http://jsfiddle.net/goodegg/phj8q/
(although there is a mistake in it).
EDIT
Go here for my forked version of the code: http://jsfiddle.net/annabels/7xksa/

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

Categories