I have an HTML form which selects towns from a MYSql Db and through PHP "foreach" returns an array of results, which are then seen in the dropdown.
I would like to then be able to click on one of the returned results within the dropdown and use it to populate a table further on in the code as a PHP variable (or another way if possible). I have attached the code. The dropdown works, but the town that is clicked on does not return the expected result, but rather always returns the last result in the list, making me think that the JS portion of my code is incorrect. I have very limited knowledge of JS, so I may very well be approaching this totally incorrectly.
Any input appreciated.
<div class="container">
<div class="table-responsive">
<table class="table table-hover tablewd">
<thead>
<tr>
<th>Origin Town</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form>
<div class="form-group">
<select class="form-control" id="colltown" name="colltown">
<?php {
$sql1 = "SELECT * FROM town_info";
$sth1 = $pdo->prepare($sql1);
$sth1->execute();
$towns = $sth1->fetchAll(PDO::FETCH_ASSOC);
foreach ($towns as $town) {
echo "<option value='$town[id]'>$town[place_name]</option>";
}
}?>
<script>
function myFunction() {
document.getElementById("colltown").value;
}
</script>
<button onclick="myFunction()">
<?php echo $origin_town = $town[place_name];?>
</button>
</select>
</div>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
Add change event to select and use this to grab the selected value
document.querySelector('select').addEventListener('change', function() {
const selectedValue= this.value;
console.log(selectedValue);
});
<select>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
I am trying to update a session value by dropdown onchange event and use this session value to a second page. For this I have added following dropdown list and a submit button.On submit button press I am updating the session value.It is working sometime but most often it is giving the previous session value even after changing the dropdown list option.Whats wrong with it
<?php
session_start(); // start session before output
if( isset($_POST['submit']) ) { // some other page is posting to this page?
// save values from other page to session
$_SESSION['amount'] = $_POST['select_amount'];
}
?>
<form name="myForm" action="/thanks" method="POST">
<table> <tr> <td style="width:272px;">
<select name="select_amount" id="select_amount" onchange="submit()">
<option value="0">select a listing type</option>
<option value="10">Premium Listings </option>
<option value="20">Premium Blogs </option>
<option value="30">1 week sticky </option>
</select></td>
<td style="text-align:left;color:gray;"><span style="color:crimson;">*
</span>Select a listing type</td></tr> </table>
<table> <tr>
<input type="submit" name="submit" class="button_add" onsubmit="return
validateForm()">
</form>
if you want to change session value using on change then no need to form submit, use ajax then you can do it easily
Step1: create your main file like this
<?php
session_start(); // for show your session value
print_r($_SESSION); // remove this after check
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form name="myForm" action="/thanks" method="POST">
<table>
<tr>
<td style="width:272px;">
<select name="select_amount" id="select_amount" onchange="update_session_value(this.value)">
<option value="0">select a listing type</option>
<option value="10">Premium Listings</option>
<option value="20">Premium Blogs</option>
<option value="30">1 week sticky</option>
</select></td>
<td style="text-align:left;color:gray;">
<span style="color:crimson;">*
</span>Select a listing type
</td>
</tr>
</table>
<input type="submit" name="submit" class="button_add" onsubmit="return validateForm()">
</form>
<script>
function update_session_value(value) {
$.ajax({
type: "POST",
url: 'http://localhost/session.php', // change url as your
data: 'select_amount=' + value,
dataType: 'json',
success: function (data) {
}
});
}
</script>
then create simple session.php file
<?php
session_start();
if( isset($_POST['select_amount']) ) {
// save values from other page to session
$_SESSION['amount'] = $_POST['select_amount'];
}
?>
after on change refresh the page you can see this result
use the ajax call on change event
$("#select_amount").change(function(){
var select_amount = $("#select_amount option:selected").val();
$.post('change_session.php',{select_amount : 'store'},function(data){
if(data != ''){
alert(data);
}
});
});
put a php script on
change_session.php
I want to make that if user is select certain option(provided from database) only one value then the other option tag appear to select else for all rest of other options user have text box to enter the value. Something like the below-
<tr>
<td><span class="alert">* </span>Country:</td>
<td><select name="country_id" class="medforminput" id="country_id" onchange="getState('select_state.php?country_id='+this.value)">
<option value="Select Country">Select Country</option>
<?php
while($row4=mysql_fetch_array($coun1))
{ ?>
<option value="<?php echo $row4['country_id']; ?>">
<?php echo $row4['country_name']; ?></option>
<?php }?>
<option value="others">Others</option>
</select></td>
</tr>
<tr>
<td><span class="alert">* </span>State</td>
<?php
if($row4['country_name']=="INDIA")
{?>
<td id="statediv"><select name="state_id" class="medforminput" id="state_id" onchange="getCity('select_city.php?state_id='+this.value)">
<option value="">Choose State</option>
</select></td>
<?php else {
<td id="statediv"><input type="text" name="state_id" class="medforminput" id="state_id"/>
</td>
<?php }?>
</tr>
I am getting nothing what wrong in the concept?
I want to display select tag where user choose the "INDIA" else text box to enter the state.
You need to write an onChange event handler in javascript that tests the option selected, then either displays the dropdown or textbox in a dynamic div.
I'm going to use jQuery because it's a LOT less code.
Example:
<select name="country_id" class="medforminput" id="country_id" >
<!-- options go here -->
</select>
<script language="javascript">
$("#country_id").change(function() {
if ($(this).val() == 'India') { // put the country id here instead of string comparison
$("#stateInput").html(getStates());
} else {
$("#stateInput").html("<input type='text' id='stateId' name='stateId' />");
}
});
</script>
Please excuse the pseudocode - I didn't want to make it excessively long.
I'm new to php/ajax and to an extent sql. I'm trying to add a dynamic drop down box which when select will either load up another drop down box with dates or another text box. Can someone point me towards some simple examples that are not very confusing. I understand that ajax is best for this.
script
function showfield(name){
if(name=='byreturn')document.getElementById('div1').style.display="block";
else document.getElementById('div1').style.display="none";
}
if(name=='forwardorder')document.getElementById('div2').style.display="block";
else document.getElementById('div2').style.display="none";
}
function hidefield() {
document.getElementById('div1').style.display='none';
}
page
<tr><td> <body onload='hidefield()'>
Choose Delivery Type </td>
<td> <select name = 'elementtype1'id='elementtype1' onchange='showfield(this.options[this.selectedIndex].value)'>
<option value='forwardorder'>Forward Order</option>
<option value='byreturn'>By Return</option>
</select></td>
<td>
<div id='div1'>Enter By Return Date<input type='text''name='whatever1' />
</div>
<div id='div2'>
<td>Capacity</td>
<td><select name='deliveryDate'>
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
<option value='" . $x[cap] . "'</option>;
</div>
</td></tr>
This is very simple
<select name="first" onChange="populateNextBox(this)">
<options value="1">Microsoft</options>
<options value="2">Oracle</options>
</select>
<div id="populate"></div>
When user select the value from the drop down
required java script function
function populateNextBox(e) {
alert(e.value); //will print the selected value
//used jquery for populating data
$.post('ajax/test.php?id='+e.value, function(data) {
$('#populate').html(data);
});
}
//Your ajax/test.php will create the content for the dropdown
I have this problems. using html and php.
May I know how to do this. I have 2 drop down, eg A and B. Drop down B is depend to the drop down A. Example, A have these options which will be called from dbase(no prob with this, tq) (Jack, Carol), and B wil have options depend on A: if select Jack(T1, T2, T3), if select carol(T1,T2,T3,T4,T5).
Here are the sample interface.
Can someone help me with this?
thank you.
U need to Work with Ajax In this Case. Without Refreshing the Page Selecting any of the A column will give u corresponding B column Value. For Example
<form method="post" name="form1">
<table border="0" cellpadding="0" cellspacing="0" width="60%"><tbody>
<tr>
<td width="150">Country</td>
<td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option> </select></td>
</tr>
<tr>
<td>State</td>
<td>
<p id="statediv">
<select style="background-color: #ffffa0" name="state"><option>Select Country First</option> </select></td>
</tr>
<tr>
<td>City</td>
<td>
<p id="citydiv">
<select style="background-color: #ffffa0" name="city"><option>Select State First</option> </select></td>
</tr>
</tbody></table>
</form>
As you can see above, in the onChage event of the country drop down getState() function of the javascript is called which change the options values the State drop down, let’s look at the code the getState() function.
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The code of the PHP file findState.php, which populate the options in the drop down of the state which is fetched from Ajax , is given below
<? $country=intval($_GET['country']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,statename FROM state WHERE countryid='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?=$country?>,this.value)">
<option>Select State</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<?=$row['id']?>><?=$row['statename']?></option>
<? } ?>
</select>
In the above state dropdown, getCity() function is called in onChage event with countryId and stateId parameter, now let’s look at the code of the getCity() function
function getCity(countryId,stateId)
{
var strURL="findCity.php?country="+countryId+"&state="+stateId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
In the above ajax function, findcity.php is called and this PHP file populate the city dropdown according to the supplied parameters country and state from get method. Now let’s look at the code of findcity.php,
<?php $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,city FROM city WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);
?>
<select name="city">
<option>Select City</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['city']?></option>
<?php } ?>
</select>
And thats all, the triple drop down list of city, country and state using Ajax and PHP will be populated.
You will need Ajax bound to the onClick of Drop Down A that is set to populate the inner HTML of Drop Down B
Ajax is "cool" thing right now so everyone is going to say use ajax. I'm going to say you don't NEED ajax. An alternative would be to disable the second form. When the first select is submitted/changed the page reloads adding something to the querystring e.g. ?a=jack and the second select is populated with the correct values.
Now any pages linking to ?a=jack will automatically populate the second select, when with ajax youd have to write even more javascript code.
I'm not saying don't use ajax, im just giving a different, most likely easier alternative.
Only use ajax when it really helps the user experience.
ONE way to do it if you absolutely do not want to use jQuery nor javascript:
<form action="?step=2" method="post">
<select name="name">
<option if($_POST['name'] == 'Jack'){echo ' selected="selected" ';}>Jack</option>
<optionif($_POST['name'] == 'Carol'){echo ' selected="selected" ';}>Carol</option>
</select>
<?php if($_GET['step'] == 2){?>
<select name="b">
<option>1</option>
<option>2</option>
<option>3</option>
<?php if($_POST['name'] == 'Carol'){?>
<option>4</option>
<option>5</option>
<?php } ?>
</select>
</form>
<?php } ?>
<input type="submit" name="next" value="Next" />
You will have to breack the form/page into steps. And the whole form needs to be re-populated as the pages are reloaded.
Hope this can be of assistance to you
I think this tutorial explains what you're trying to achieve: Dependable Dropdown Menus with jQuery and PHP