In my website I have drop down box and I made event to know which element selected from the user .. and it works . I can retrieve the value and print it on the screen using id attribute !! This function will work when user Select from drop down
<script>
function SelServ(){
var x = document.getElementById("services").value;
document.getElementById("chosenServ").innerHTML =x;
}
</script>
The drop down box reads from database
echo "<select name = \"services\" id = \"services\" onchange = \"SelServ()\">";
//my connection
$myCon = new mysqli("localhost","root","","mss");
if(mysqli_connect_errno()){
printf("Connect Failed : %s
",mysqli_connect_error());
}
else{
$sql = "SELECT ServID ,ServName FROM service";
$result = mysqli_query($myCon,$sql);
if($result){
while($StaffArr = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$servName = $StaffArr['ServName'];
$ServiceID = $StaffArr['ServID'];
echo "<option value = \"".$ServiceID."\">".$servName."</option>";
}
}
else{
printf("Couldn't retrive records ! <br /> %s",mysqli_error($myCon));
}
}
echo "</select>";
And I'm using div to retrieve selected item
$servIDHTML = "<div id = \"chosenServ\"></div>";
I want to extract the value of id and included in sql statement to affect in seconed drop down box in the same page !! Any idea?
You must use ajax:-
Let's say you have 2 dropdown parent_id and children:-
<select name="parent_id" id="parent_id">
<option value="">Select ID</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="child" id="child">
<option value="">Select Children</option>
</select>
Include the following ajax at the bottom of your page:-
<script>
$('#parent_id').change(function(){
var parentId = $('#parent_id').val();
$.ajax({
url: "ajax.php",
type: "post",
data: {parentId: parentId},
success: function(data) {
$('select#child').html(data);
}
});
});
</script>
PHP file where you can execute the SQL query based on your selection and return the result in options:-
ajax.php
if($_POST){
$parentId = $_POST['parentId'];
$sql = "SELECT * FROM TABLENAME WHERE parent_id=".$parentId;
/*
Fetch the result, prepare options for select and echo them
*/
}
</div>