Populate dropdown2 from onChange event of dropdown1 - javascript

I need to write a code where i need to populate a dropdown1 from mysql table based on the selection of another dropdown which also where in need to give values of dropdown as numeric value as item id from mysql table , but script.js not accepting any numeric value .Am quite new to this concept please help me to resolve this issue, thank you
HTML PART
<div>
<select class="custom-select" style="width: 150px;" id="dropdown1" onchange="onChange()">
<option selected disabled>Select Role </option>
<?php
enter code here
$sql = "SELECT * FROM category";
$result = $conn->query($sql);
//Populate dropdown2 from onChange event of dropdown1
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()){
echo "<option class='dropdown-item' value='".$row["id"]."'>".$row["name"]."</option>";
}
} else{
echo "Sorry No Role Availabe for Now";
}
$conn->close();
?>
</select><br/>
<span id="choosen"></span>
</div>
JS PART
<script>
function onChange(){
var idforquery =document.getElementById('dropdown').value;
document.getElementById("choosen").innerHTML="
// Here we generate another dropdown of behalf of selected dropdown option
<div>
<select class="custom-select" style="width: 150px;" id="dropdown1">
<option selected disabled>Select Role </option>
<?php
$sql2 = "SELECT * FROM sub_category WHERE cat_id =idforquery;";
$result = $conn->query($sql2);
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()){
echo "<option class='dropdown-item' value='".$row["id"]."'>".$row["name"]."</option>";
}
} else{
echo "Sorry No Role Availabe for Now";
}
$conn->close();
?>
</select><br/>
<span id="choosen1"></span>
</div>";
}
</script>

This is not going to work. PHP code is only executed when the client loads the page. If you want the <option> tags to change dynamicaly after the page has loaded, you need to use an asynchronous request (AJAX).
Here is a guide on how to use AJAX requests using PHP and jQuery.

Related

retain drop down selection after form submission

I have an HTML form with multiple drop down menu fields that get populated looping thru arrays for select data common between multiple fields.
<label>Techician:</label>
<select name="rcvTech" id="rcvTech">
<option value="0">--Select Technician--</option>
<?php
foreach ($tech as $t) {
echo "<option value='$t'>$t</option>";
}
?>
</select>
What could I do to have the selected data for all drop down menus retained when the form is submitted so that if there are any errors to correct the user would not have the tedious task of having to re-select each field over?
Solution adapted from user5748817's post below:
<label>Receiving techician:</label>
<select name="rcvTech" id="rcvTech">
<option value="0" selected="selected">--Select Technician--</option>
<?php
foreach ($tech as $t) {
echo "<option value='$t'";
if (isset($_POST['submitted']) && $_POST['rcvTech'] == $t){
echo " selected";
}
echo ">$t</option>";
}
?>
</select>
To be able to handle the multiple selected options you would need to collect the data as an array. So change the select name to rcvTech[]. When validating the data submitted, collect it in a session to be able to get the submitted values.
<label>Techician:</label>
<select name="rcvTech[]" id="rcvTech">
<option value="0">--Select Technician--</option>
<?php
foreach ($tech as $t) {
if (in_array($t, $_SESSION['submitted'])) $selected=" selected";
echo "<option value='".$t."' ".$selected.">".$t."</option>";
}
?>
</select>

Dynamically populate 3 dropdowns based on the selection in first dropdown

I have 4 dropdowns. Magazines, DD1, DD2, DD3. The dropdowns DD1, DD2, DD3 needs to be auto populated dynamically with the selection of a value in Magazine dropdown. The dropdowns DD1, DD2, DD3 are not dependent on each other. They purely depend on value in Magazines dropdown.
On the selection of dropdown 1 value, php ajax has to make call on mysql. I need to implement 3 different mysql queries in the background for 3 dropdowns.I surfed in net and all dropdowns are related to the previous dropdowns. For Example.
Can anybody guide me with proper link or proper idea to do this.
A quick workaround using javascript onchange:
form:
<select name="dd1" id="dd1" class="form-control" onChange="getDD2(this.value);">
<option value="" selected="selected">-select-</option>
</select>
javascript:
function getDD2(id){
if(id==""){
alert("Please select any dd1!");
}else{
var url = 'getdd2.php?id='+id;
$('#dd2container').load(url);
}
}
and in getdd2.php
$id = $_REQUEST['id'];
$dd= "SELECT * FROM prefix_dd2 WHERE id='$id'";
$founddd1 = $dbh->query($dd);
$res = $founddd1->fetchAll();
if(count($res)<=0){
echo '<select name="dd2" class="form-control" id="dd2">';
echo '<option value="select">No dd</option>';
echo "</select>";
}else{
echo '<select name="dd2" class="form-control" id="dd2" onchange="getDD3($id)">';
echo '<option value="select" selected="selected">-select-</option>';
foreach($res as $dd2):
echo '<option value="'.$dd2['id'].'">'.$dd2['dd2_name'].'</option>';
endforeach;
echo "</select>";
}
DD2 select in your form would be:
<div id="dd2container">
<select name="dd2" class="form-control">
<option value="" selected="selected">--select--</option>
</select>
</div>
Now you can make getDD3() function like I did getDD2() above. I hope this may help.
If you want to populate three select at one go, you can put all the three select box in the getdd2.php and query the database for each base on the data from the first select box.

Add more fields function and populate second combobox based on first combobox can be run for all row insert

I have jQuery PHP function to add more fields.
HTML
<div class="faculty_row">
<select name="search_category" id="search_category_id">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
<input type="text" name="message[]">
</div>
Add More
JS
jQuery(document).ready(function($){
$("#add_more").on('click', function(e){
e.preventDefault(); // Prevent Default the event
var clone = $(".faculty_row").eq(0).clone(); // clone only first item
$("#faculty_wrapper").append(clone); // append it to our form
});
Then I have jQuery Populate Second Combobox based on First Combobox
html
<select name="search_category" id="search_category_id">
<option value="" selected="selected"></option>
<?php
$query = "SELECT * FROM t_category ORDER BY category_name ASC";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['category_id'];?>"><?php echo $rows['category_name'];?></option>
<?php
}?>
</select>
<span id="show_sub_categories" align="center">
JS
jQuery(document).ready(function($){
$('#loader').hide();
$('#show_heading').hide();
$('#search_category_id').change(function(){
$('#show_sub_categories').fadeOut();
$('#loader').show();
$.post("get_chid_categories.php", {
parent_id: $('#search_category_id').val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
});
return false;
});
function finishAjax(id, response){
$('#loader').hide();
$('#show_heading').show();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function alert_id()
{
if($('#sub_category_id').val() == '')
alert('Please select a sub category.');
else
alert($('#sub_category_id').val());
return false;
}
Each function is run perfectly. How can I combine that 2 function to be 1? So the populate Second Combobox based on First Combobox can be run on next row if I click button Add More.

How to remove an empty string from an array. I am not sure weather it is from PHP or Ajax

I am using Ajax in order to display drop-down list when a product group is selected. My Ajax returns a list from the query page(dropd.php). However the problem is the array consists of some empty space between each element. Hence when I did inspect in chrome below is the output I am getting,
<option value="1">Gear pumps</option>
<option></option>
<option value="2">Piston pumps</option>
<option></option>
How could I remove "<option></option>" from the drop-down list? If I take option tag out from html what I receive is;
Gear pumps^piston pumps^vane pumps...etc
If you can notice the space(^).
Ajax code
<script>
$(document).ready(function(){
$('#sel1').on('change', function(){
$.post("dropd.php",{vals:$("#sel1 option:selected").text()},
function(data){$.trim($("#sel2").html( data ));});
});
});
</script>
dropd.php
<?php
require('../config/connection.php');
if($_POST['vals']){
$values = mysqli_real_escape_string($dbc,$_POST['vals']);
$query = "SELECT * FROM prdct_categories WHERE product = '$values'";
$result = mysqli_query($dbc, $query);
?>
<option value="">Select subgroup</option>
<?php
foreach($result as $row)
{ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subgroup']; ?><option/>
<?php
}
}
mysqli_close($dbc);
?>
Ajax data goes here
<div class="form-group">
<label for="inputsubprdctgrp" class="col-sm-4 control-label" >Product Subgroup</label>
<div class="col-sm-8">
<select class="form-control" id="sel2" >
</select>
</div>
</div>
Thanks in advance.
There may be 2 issues:
The SQL result gives an empty value which can be fixed by using the array_filter() method:
$new_result = array_filter($result);
You wrote option/ instead of **/option
Hope this helps :)
just dont put those values in options if it is blank..
you can use below code.
$result = mysqli_query($dbc, $query);
?>
<option value="">Select subgroup</option>
<?php
foreach($result as $row)
{
if(trim($row['subgroup'])!=''){
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subgroup']; ?><option/>
<?php
}
}
mysqli_close($dbc);
?>
Just use `
$('#sel2').find('option:empty').remove();`
after you load content from ajax,
if you want to do it in javascript, otherwise avoid it in PHP in the first place.

How to display records from database in select onchange event

I'm a beginner in coding of PHP, just want to ask how to display records using the script below?
$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option value = "'.$row['rfq'].'">'.$row['rfq'].'</option>';
}
?>
<form>
<select>
<option value="ALL">ALL</option>
<?php echo $option; ?>
</select>
</form>
ALL option is load when the page runs and displays all the record in table, and when I choose 13-001 I want to display the record of 13-001. How to do that?
Use AJAX, dude. It's very cool and easy.
An Example
Another good example using jQuery
Do the same thing again but use a WHERE clause.
Also i hope you are using mysqli not mysql - it will be gone soon.
<form>
<select name='rfq' onChange='this.form.submit()'>
<option></option>
etc...
</select>
<input name='Submit' value='Submit' type='submit'>
</form>
<?php
if(isset($_POST['submit'])) {
$rfq = $_POST['rfq'];
$query = "SELECT * FROM table WHERE rfq = '$rfq'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo "{$row['id']} <br>";
echo "{$['field1']} <br>";
echo "{$row['field2']} <br>";
etc..
}
}
?>
You need to format it of course, but that should get you started.

Categories