hi i'm using select2 to style my dependent dynamic dropdown list on my php file, the problem is when i select a value from 1st dropdown to fetch data from mysql DB to 2nd dropdown list it goes to it's default style so i need some solution to solve the problem here is my files.
select2 script:
<script type="text/javascript">
$(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>
index.php:`
<form name="form1" action="test.php" method="post">
<table>
<tr>
<td>
<select name="brand" id="branddd" class="js-example-basic-single" required>
<option disabled selected required >brand</option>
<?php
$res=mysqli_query($link,"select * from brand");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select name="model" id="model" class="js-example-basic-single" required>
<option disabled selected required >model</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
script to fetch DB values:
<script type="text/javascript">
function change_brand()
{
var xmlhttp=new XMLHttpRequest () ;
xmlhttp.open("GET","ajax.php?brand="+document.getElementById("branddd").value,false) ;
xmlhttp.send(null) ;
document.getElementById("model").innerHTML=xmlhttp.responseText ;
}
$(function(){
$('#branddd').on('change',function(){
this.value && // if value!="" then call ajax
$.get('ajax.php',{brand:this.value},function(response){
$('select[name="model"]').html(response);
});
});
});
</script>
ajax.php:
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"test_db");
$brand=$_GET["brand"];
if($brand!="")
{
$res=mysqli_query($link,"select * from model where brand_id=$brand");
echo "<select>";
while($row=mysqli_fetch_array($res))
{
echo "<option>"; echo $row["name"]; echo "</option>";
}
echo "</select>";
}
?>
This is your styled select element:
<select name="model" id="model" class="js-example-basic-single" required>
You need to add the name, id, and class attributes to your PHP echo. Something like this:
echo "<select name=\"model\" id=\"model\" class=\"js-example-basic-single\" required>";
But a much better way would be to not write out a new select element and replace it with the html function. Instead, output the data from your PHP page as a JSON object, then add those options to the select element.
JSON object:
{
"option1": "Data A",
"option2": "Data B",
"option3": "Data C"
}
JavaScript:
function change_brand() {
$.ajax({
url: "ajax.php?brand="+document.getElementById("branddd").value,
dataType: "json",
success: function(data) {
var name, select, option;
select = document.getElementById('model');
// Clear the old options
select.options.length = 0;
// Load the new options
for (name in data) {
if (data.hasOwnProperty(name)) {
select.options.add(new Option(data[name], name));
}
}
}
});
}
Related
I have a MySQL database table which has a unique ID identifier for each line:
id text cat
4 abc 1
233 bbb 2
45 efa 1
Using PHP, I show an HTML table where you can see the TEXT and CAT fields.
Each row of the table is shown using a "while" loop.
As you can see, I also store the IDs in the array $val.
<?php
....
$val = array();
while($objResult = mysql_fetch_array($objQuery)){
$val[] = $objResult["id"];
?>
<table>
<tr>
<td><?php echo $objResult["text"];?></td>
<td><?php echo ''.$objResult["cat"].'';</td>
<tr>
<?php
}
?>
</table>
Now comes the tricky part.
Using JQuery, I would like to be able to click on the CAT cells in the html table and open a dialog window where I can change the value of CAT.
Here is the form:
<form action="modcat.php" method="POST" id="modcat">
<table>
<tr>
<td>
<select id="cat">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<input type="hidden" name="val" value="<?php
for ($i = 0; $i < 1000; $i++) {
echo $val[$i];
}
?>">
</td>
</tr>
</table>
</form>
<script>
$(document).ready(function () {
$("a#open").click(function () {
$('#finestra').dialog("open");
return false;
});
$('#finestra').dialog({
modal: true,
autoOpen: false,
buttons: [{
text: "modifica",
click: function () {
submitform();
$(this).dialog("close");
}
}, {
text: "annulla",
click: function () {
$(this).dialog("close");
}
}]
});
function submitform() {
$('#modcat').submit();
}
});
</script>
As you can see, I am trying to send to the form the corresponding value of ID (through a hidden input).
As it turns out, I put together all the IDs of all the table in the array $val.
How can I send to the form just the one which is chosen?
You can add the id to the html someplace, retrieve it in the click function, and add it to the form before submitting.
Here, i am adding the id as a data attribute, i also changed the id on the a element to a class, since your rendered html will contain multiple a elements, and ids should be unique
while($objResult = mysql_fetch_array($objQuery)):?>
<table>
<tr>
<td><?= $objResult['text'];?></td>
<td>
<a href="#" class="open" data-id="<?=$objResult['id'];?>">
<?=$objResult['cat'];?>
</a>
</td>
<tr>
</table>
<?php endwhile;
For the form, dont prepopulate the hidden field, just give it an id so its easy to target in js:
<form action="modcat.php" method="POST" id="modcat">
<table>
<tr>
<td>
<select id="cat">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<input type="hidden" name="val" id="hidden-id">
</td>
</tr>
</table>
</form>
Then in your js update the value from the data attribute:
$(document).ready(function () {
$("a.open").click(function () {
var clickedLink = $(this); //get clicked link
var id = clickedLink.data('id'); //extract id from data attribute
$('#hidden-id').val(id); //update hidden field value with id
$('#finestra').dialog("open");
return false;
});
...
view code i have : file one to show data two select box second select box depand on the first select box value
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("register",$con);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#category").change(function(){
var value=$("#category option:selected").val();
$.ajax({
type:'post',
url:'subcat.php',
data:{ kvalue : value },
datatype:'json',
success:function(data){
alert(data);
$("#response").html(data);
}
})
})
})
</script>
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>category:</td>
<td><select id="category">
<option>Select Category</option>
<?php
$query=mysql_query("select * from category");
while($row=mysql_fetch_array($query)){
?>
<option value="<?php echo $row['category'];?>"><?php echo $row['category'];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Sub cat:</td>
<td><select >
<option >dependent dropdown</option>
<option id="response"></option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
another page for ajax call:
This page return the data in json format to first file .problem is that i have one select box there i want to get these value in my option but i m getting this value and if m going to select on then all value auto selectrd
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("register",$con);
$val=strtolower($_POST['kvalue']);
if($val=='mobile'){
$query=mysql_query("select mobile from subcat");
while($row=mysql_fetch_array($query)){
$row[] = $r;
print json_encode($row);
echo $row['mobile']."</br>";
}
}
problem``
i want to fetch data from json in html option but i get the value but it all in selected form how can i get or select the value one which i want??
check this demo code which select option update and your your connection and query , i just set manually data for test. this is your html file
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#category").change(function () {
var value = $("#category option:selected").val();
$.ajax({
type: 'post',
url: 'subcat.php',
data: {kvalue: value},
datatype: 'json',
success: function (data) {
alert(data);
$("#response").html(data);
}
})
})
})
</script>
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>category:</td>
<td><select id="category">
<option>Select Category</option>
<option value="mobile">Mobile</option>
<option value="TV">Tv</option>
<option value="Phone">Phone</option>
</select>
</td>
</tr>
<tr>
<td>Sub cat:</td>
<td>
<select id="response">
<option>dependent dropdown</option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
and this is your subcat.php file .i set manually data for test. if you want to select depend your option data just update your query
<?php
//$con=mysql_connect("localhost","root","root");
//mysql_select_db("register",$con);
$val = strtolower($_POST['kvalue']);
if ($val == 'mobile') {
//$query=mysql_query("select mobile from subcat");
$data = array('Option1', 'Option2', 'Option3');
foreach ($data as $value => $key) {
echo '<option value="' . $value . '">' . $key . '</option>';
}
}
if you select second option value using ajax send option then update query like
//$query=mysql_query("select mobile from subcat where subcat = '$val'");
and this is my demo data so need to replace your sql data
I am trying to create a dependent dynamic drop down box on three input fields. At the moment the each input field is getting their data from their individual tables called tour_type, countries and destination. This is the form:
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id` = ?"); //what should i put in here?
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
echo "<option value='$cid'>".$name."</option>";
}
?>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `destination` where `countries_id` = ?");//what should i put in here?
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
echo "<option value='$destination_id'>".$name."</option>";
}
?>
</select>
This is the javascript at the top of the form
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$(".destination").html(html);
}
});
});
});
</script>
Finally these are the 3 tables i.e. tour_type, countries and destination respectively:
Can anyone help me on this?
How do I make each drop down box dependable on each other? For e.g. If i select Culture on the 1st drop down, then only Holland and Belgium should show in the 2nd drop down. So now if i select Holland from 2nd drop down, then Amsterdam should show in the 3rd drop down.
This is the ajax.php which i am not too sure if it is right.
<?php
include('../config.php');
if($_POST['']) //what should i put in here?
{
$id=$_POST['']; //what should i put in here?
$sql=mysql_query //this is where i do not know what to put;
while($row=mysql_fetch_array($sql))
{
//And what should i be placing here
}
}
?>
This is what the web front end form looks like after implementing the code provided by dianuj. I still can not select the 2nd and 3rd drop down boxes:
So first you have the tour type select box. So just move the code for fetching countries based on tour type to ajax.php. Also include one more parameter to distinguish which type(tour type,country etc) you are posting. so you will get the id and based on the type parameter you can fetch from different tables. Then create a selectbox HTML snippet and output it. This will return for the AJAX call and you can insert the HTML.
You can use ajax get here and can use the shorthand version like
$.get('ajax,php?id=idhere&type=country', function(data) {
$('#country_result').html(data);
});
Where result is the id of div to which the select box has to be inserted.
So the HTML part will be like
<div id="country_result"></div> //Country select box goes here
<div id="destination_result"></div> //Country select box goes here
The simplest approach is to fetch select options from the server when the selections change, like so:
$('#tour_type').change(function() {
// load country options
});
$('#country').change(function() {
// load destination options
});
The server should simply return a snippet of HTML containing the available options for country and destination.
here you go you have to fetch the options from the ajax.php do not place the query in second dropdown
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" >--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="">-- Select --</option>
</select>
initially country and destination drop down should be empty here your js goes
$('#tour_type').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_countries=1",
success: function(html)
{
$("#country").append(html);
}
});
});
$('#country').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_destination=1",
success: function(html)
{
$("#destination").append(html);
}
});
});
And your ajax.php
<?php
if($_REQUEST['get_countries']){
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id`=".$_REQUEST['id']);
$countries="";
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
$countries.= "<option value='".$cid."'>".$name."</option>";
}
echo $countries;
}elseif($_REQUEST['get_destination']){
$destination="";
$sql=mysql_query("SELECT * FROM `destination` where `country_id` =".$_REQUEST['id'])
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
$destination.= "<option value='".$destination_id."'>".$name."</option>";
}
echo $destination;
}
?>
Hope it works fine
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required onchange="get_country($(this).val())">
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required onchange="get_destination($(this).val())">
<option value="" selected="selected">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
</select>
<script>
function get_country(tour_type)
{
$.post("ajax.php",{get_country:tour_type},function(data){
var data_array = data.split(";");
var number_of_name = data_array.length-1;
var value;
var text;
var opt;
var temp_array;
for(var i=0; i<number_of_name; i++)
{
value=temp_array[i];
//alert(value);
text=temp_array[i];
opt = new Option(text,value);
$('#country').append(opt);
$(opt).text(text);
}
$("#country").prop("disabled", false);
});
}
//same way script for getting destination
</script>
// now in ajax file
if(isset($_POST["get_country"]))
{
$tour_type = str_replace("'","",stripslashes(htmlentities(strip_tags($_POST["get_country"]))));
$country_select = mysql_query("select * from country where tour_type_id = '$tour_type'");
$country="";
while($country_row = mysql_fetch_array($country_select))
{
$country = $country.$country_row["country"].";";
}
echo $country;
}
// same way ajax for destination
I have a problem in hiding a list menu generated dynamically with php. My browser didn't hide it. I am using Firefox; the code is like this:
<div id="groupstd">
<br />
<select style="text-align:center;" name="std3">
<option value="Select" selected="selected">Please Select Student.no#3</option>
<?php
$result=Connect();
if($result>0)
{
while($row = mysql_fetch_array($result))
{
echo '<option value=$row[\'Roll#\'].\'i-\'.$row[\'Batch\']>$row[\'Roll#\'].\'i-\'.$row[\'Batch\']</option>';
}
}?>
</select>
</div>
<div id="grpstd">
<br />
<select style="text-align:center;" name="std4" id="std4">
<option value="Select" selected="selected">Please Select Student.no#4</option>
<?php
$result=Connect();
if($result>0)
{
while($row = mysql_fetch_array($result))
{
echo '<option value=$row[\'Roll#\'].\'i-\'.$row[\'Batch\']>$row[\'Roll#\'].\'i-\'.$row[\'Batch\']</option>';
}
}?>
</select>
</div>
I am using JQuery to hide like this:
$(document).ready(function()
{
$('#grpstd').hide();
$('#groupstd').hide();
});
try doing this after the dom is ready as using this:
$(document).ready(function() {
$('#grpstd, #groupstd').hide();//using two elements using one statement
});
When are you trying to hide the divs? You will need to wait until at least the document is ready:
$(document).ready(function() {
$('#grpstd').hide();
$('#groupstd').hide();
});
Did you try this?
$(document).ready(function() {
$('#grpstd, #groupstd').hide();
});
or
$(function() {
$('#grpstd, #groupstd').hide();
});
Languages: PHP,JQuery,MySQL
The question is "simple", I have a triple dependency with php and jquerys, the code works great, for inserting new information, but now I would like to make an update, so I need to load the current information first and I don't figure it out how to, I add some parts of the code, if any more parts needed ask me before voting me down please.
Code is something like this:
<tr>
<td class="main"><?php echo ENTRY_COUNTRY; ?></td>
<td class="main">
<select id="country" name="country">
<option value="0">Select One...</option>
</select>
</td>
</tr>
<tr>
<td class="main"><?php echo ENTRY_STATE; ?></td>
<td class="main">
<select id="state" name="state">
<option value="0">Select One...</option>
</select>
</td>
</tr>
<tr>
<td class="main"><?php echo ENTRY_CITY; ?></td>
<td class="main">
<select id="city" name="city">
<option value="0">Select One...</option>
</select>
</td>
</tr>
The three are loaded from a db in mysql, by actions like:
<script type="text/javascript">
$(document).ready(function(){
cargar_paises();
$("#country").change(function(){dependencia_estado();});
$("#state").change(function(){dependencia_ciudad();});
$("#city").change(function(){dependencia_zip();});
$("#state").attr("disabled",true);
$("#city").attr("disabled",true);
});
function cargar_paises()
{
$.get("scripts/cargar-paises.php", function(resultado){
if(resultado == false)
{
alert("Error");
}
else
{
$('#country').append(resultado);
}
});
}
function dependencia_estado()
{
var code = $("#country").val();
$.get("scripts/dependencia-estado.php", { code: code },
function(resultado)
{
if(resultado == false)
{
alert("No se encontraron provincias para ese pais");
$("#state").attr("disabled",true);
document.getElementById("state").options.length=1;
}
else
{
$("#state").attr("disabled",false);
document.getElementById("state").options.length=1;
$('#state').append(resultado);
}
}
);
}
function dependencia_ciudad()
{
var code = $("#state").val();
$.get("scripts/dependencia-ciudades.php?", { code: code }, function(resultado){
if(resultado == false)
{
alert("Error");
}
else
{
$("#city").attr("disabled",false);
document.getElementById("city").options.length=1;
$('#city').append(resultado);
}
});
.....
Thanks for everything ;) sorry for the english.
I guess you want something like this:
On the main page:
<script>
document.ready = function() {
fillBasicInformation();
}
</script>
Now you would have to define a fillBasicInformation function, as follows:
//this should only be called in edit mode
fillBasicInformation = function() {
//First fill country select
//select the specific country
//Fill state select
//select specific state
//fill city select
//select specific city
//now attach events to onChange event
//1
}
You have to decide now how you will get and fill your fields, adding options to the appropriate, probabl through ajax, or maybe directly on the page load and selecting the right one (using val(), for example).