Array of drop down list in html - javascript

How to change the value of dropdown dinamically.
here the case:
for example i have an array of dropdown and has 2 names on it, like name1 and name2,
the name 1 has grade and also the name2.
what i want to do is change the first dropdown which has the value of name and
i want the second dropdown change automatically according to his grade.
Like:
John -> 90
Paul -> 80
please help me to find the index of array and the selected value of dropdown using javascript. thanks in advance.
<script>
function Change2(a){
var options1= document.getElementById('stuname[]').options;
var options2= document.getElementById('stugrade[]').options;
for(i = 0; options1.length;i++){
if(options1[i].selected == true){
options2[i].selected = true;
}
}
} // what I want is, if I change the first dropdown in row 1, the 2nd dropdown should change too, and same in row 2.
</script>
<?php
$getlist= mysql_query("SELECT * FROM STUDENTS");
while($row = mysql_fetch_assoc($getlist)){
print "<select id = 'stuname[]' name = 'stuname[]' class = 'text4' onchange = 'Change2(this.value);'>";
$getname = mysql_query("SELECT * FROM NAME");
while($row = mysql_fetch_assoc($getname)){
$name = $row['name'];
print "<option value = '$name'>$name</option>";
}
print "</select>";
print"<select id = 'stugrade[]' name = 'stugrade[]' onchange = 'Change2(this.value);'>";?>
<?php
$getgrade = mysql_query("SELECT * FROM GRADE");
while($row = mysql_fetch_assoc($getgrade)){
$grade = $row['grade'];
print "<option value = '$grade'>$grade</option>";
}
print "</select><br>";
}
?> // heres my code.. edited

This is a common approach to solve this kind of issues, differently you need change querys and names accordingly
JS file
$(document).ready(function(){
getfirstSelect();
})
function getSecondSelect() {
var firstDropDownSelectedID = $('#firstSelect option:selected').val();
$.ajax({
type: "POST",
url: "getSecondDropDownOptions.php",
data: "firstDropDownSelectedID="+firstDropDownSelectedID
}).done(function (result) {
//alert(result)
$("#secondSeect").html(result);
});
}
function getfirstSelect() {
$.ajax({
type: "POST",
url: "getFirstDropDownOptions.php",
data: {}
}).done(function (result) {
//alert(result)
$("#secondSeect").html(result);
});
}
getSecondDropDownOptions.php
<?
$firstDropDownSelectedID = isset($_POST['firstDropDownSelectedID']) ? (int)$_POST['firstDropDownSelectedID'] : 0;
$list2 = mysql_query("SELECT * FROM LIST2 WHERE relatedid=".$firstDropDownSelectedID);
$returnString = "";
while($row = mysql_fetch_assoc($list2)){
$returnString.= "<option value = '".$row['grade']."' >".$row['grade']."</option>";
}
print $returnString;
?>
getFirstDropDownOptions.php
<?
$list1 = mysql_query("SELECT * FROM LIST1 ");
$returnString = "";
while($row = mysql_fetch_assoc($list1)){
$returnString.= "<option value = '".$row['grade']."' >".$row['grade']."</option>";
}
print $returnString;
?>
HTML
<form name="formName">
<select name="firstSelect" id="firstSelect" onchange="updateSecondSelect()"></select>
<select name="secondSeect id="secondSeect" ></select>
</form>

Related

autocomplete multiple textboxes based on selected option on dropdown using jquery in php mysql

I have a select box that fetches the value from my database, whenever I chose a value from the select box it should show the corresponding data from my database.
For example, If i chose a research, it should show the researcher together with the date started and put it in the two existing textbox.
It is working on my first text box but the second text box is not displaying a value.
Here is my select box that fetches its values from my database;
<select id="sel_research">
<option value="0">- Select-</option>
<?php
$sql_research = "SELECT * FROM tblproposals WHERE ProposalStatus = 'Implemented' ";
$research_data = mysqli_query($con,$sql_research);
while($row = mysqli_fetch_assoc($research_data) ){
$researchid = $row['id'];
$research_name = $row['TitleOfResearch'];
echo "<option value='".$researchid."' >".$research_name."</option>";
}
?>
</select>
Here is my first textbox;
<input type="text" id="author"> //it is working here
Here is my second textbox;
<input type="text" id="datestarted" required>//it is not working here
Here is my jquery;
$(document).ready(function(){
$("#sel_research").change(function(){
var resid = $(this).val();
$.ajax({
url: 'get-researcher.php',
type: 'post',
data: {res:resid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#author").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['Researcher'];
var date_imp = response[i]['DateOfImplementation'];
$("#author").val(name);
$("#datestarted").val(date_imp);
}
}
});
});
});
Here is my "get-researcher.php"
<?php
include "includes/configs.php";
$resid = 0;
if(isset($_POST['res'])){
$resid = mysqli_real_escape_string($con,$_POST['res']);
}
$research_arr = array();
if($resid > 0){
$sql = "SELECT * FROM tblproposals WHERE id='".$resid."' ";
$result = mysqli_query($con,$sql);
while( $row = mysqli_fetch_array($result) ){
$res_id = $row['id'];
$name = $row['Researcher'];
$research_arr[] = array("id" => $res_id, "Researcher" => $name);
}
}
echo json_encode($research_arr);
I think i need to use the parseJSON but i got lost on where and how to write it.

JQuery UI Autocomplete - hide result list when no matches

I have the following problem:
I have a working implementation of JQuery UI Autocomplete that gathers results from MYSQL Database and autotomatically fills some input fields based on user's choice.
What I am currently trying to get working is the situation when you type your search and there are no search results. Right now, the last suggested search items stay visible until you click away with mouse button. I would like to be able to hide it once there are no matching results. I have read a lot on this topic but nothing seemed to work for me. This is my Javascript part:
function AutoFill(x) {
var classname = "." + x;
$(document).on('keydown', classname, function(){
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
// Initialize jQuery UI autocomplete
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "get-details.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response(data);
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected value
// AJAX
$.ajax({
url: 'get-details.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var name = response[0]['name'];
var number = response[0]['number'];
// Set value to textboxes
document.getElementById('clientname').value = name;
document.getElementById('clientnumber').value = number;
}
}
});
return false;
}
});
});
}
And this is my PHP file, that searches through the Database:
<?php
include('includes/dbconnection.php');
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM tblclients WHERE FullName like'%".$search."%' OR MobileNumber like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$response[] = array("value"=>$row['ID'],"label"=>$row['FullName'].' | '.$row['MobileNumber']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM tblclients WHERE ID=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['ID'];
$fullname = $row['FullName'];
$number = $row['MobileNumber'];
$users_arr[] = array("id" => $userid, "name" => $fullname,"number" => $number);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I don't know what I'm doing wrong...

Ajax Success Returning Commented Html Tag

I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}

Display textbox multiple row values

I have a Category dropdown selection and Mobile_Number text field. Based on my Category selection, Mobile textbox fetches DB values.
My problem is that sometimes the same Category has two or more Mobile textbox values. In this case, I want all mobile number values to be displayed in a single textbox separated by a comma (,).
Sample Table Data
Mobile_Number Category
123 IT
345 IT
456 IT
In this case when the 'IT' category is selected, then I want to display output in the text box like this below:-
123,345,456
My working code:
Ajax Page Code:
$departid = $_POST['depart']; // department id
$sql = "SELECT Mobile_Number FROM admin_panel WHERE Category=".$departid;
$result = mysqli_query($db, $sql);
$users_arr = array();
while ($row = mysqli_fetch_array($result))
{
//$userid = $row['Emp_Id'];
$name = $row['Mobile_Number'];
//$users_arr[] = array("id123" => $userid, "name123" => $name);
$users_arr[] = array("name123" => $name);
}
echo json_encode($users_arr);
Dropdown and Textbox
<select name="cat" id="cat">
<option disabled selected value> -- select an option -- </option>
<option value="1">Stencil Team</option>
<option value="2">Tooling Team</option>
<option value="3">IT</option>
<option value="4">Manager</option>
</select>
<input name="phoneNumber" id="pnum" type="text">
JavaScript:
$(document).ready(function(){
$("#cat").change(function(){
var deptid = $(this).val();
$.ajax({
url: 'ajaxdropdown.php',
type: 'post',
data: { depart: deptid },
dataType: 'json',
success: function(response) {
var len = response.length;
$("#pnum").empty();
for (var i = 0; i<len; i++) {
var name1234 = response[i]['name123'];
$("#pnum").val(name1234);
}
}
});
});
});
Your success-function has to be modified:
function(response){
var len = response.length;
var name1234 = "";
$("#pnum").empty();
for( var i = 0; i<len; i++){
name1234 += (name1234.length < 1) ? response[i]['name123'] : ',' + response[i]['name123'];
}
$("#pnum").val(name1234);
}
You can use map() to build an array of the returned name123 values, then join() it together before setting it to the val() of the input. Something like this:
success: function(response) {
var names = response.map(function() {
return this.name123;
});
$("#pnum").val(names.join(',');
}
You Don't need to execute while loop in AJAX page code you can use GROUP_CONCAT & GROUP BY in your query to get the multiple Mobile number comma separated.
Check below AJAX Page code
<?php
$departid = $_POST['depart']; // department id
$sql = "SELECT GROUP_CONCAT(Mobile_Number) AS mob_number FROM admin_panel WHERE
Category='".$departid."' GROUP BY Category";
$result = mysqli_query($db,$sql);
$row = mysql_fetch_row($result);
$name = $row[0];
echo json_encode($name);
?>
According to output of this code you also not require For loop in Javascript. You can just set the response of AJAX to phoneNumber field.
Javascript Code
$(document).ready(function(){
$("#cat").change(function(){
var deptid = $(this).val();
$.ajax({
url: 'ajaxdropdown.php',
type: 'post',
data: { depart: deptid },
dataType: 'json',
success: function(response) {
$("#pnum").val(response);
}
});
});
});
I hope this can help you (PHP):
$numbers = [];
while ($row = mysqli_fetch_array($result)) {
$numbers[] = $row['Mobile_Number'];
}
echo json_encode(implode(', ',$numbers));
and this to js:
success: function(response) {
$("#pnum").empty().val(response);
}

AJAX on IE doesnt give result onchange (ONLY IE)

my code is working on other browser yet on IE they doesnt give any result once i select my drop down button.but it change and it just give empty result.
this is my ajax
$("#book").change(function(){
var DOMBULK = $("#book").val();
$.ajax({
cache: false,
type: 'GET',
url: "store/book.php?cc="+DOMBULK,
data:{get_option:DOMBULK},
success: function(result){
$("#tybook").html(result);
}});
});
book.php
<?
$dtacc = $_GET['cc'];
$tybook= mysql_query("SELECT * FROM store WHERE status = 1 AND parentid ='$dtacc'");
while($rowtybook = mysql_fetch_assoc($tybook) or die (mysql_error()))
{ ?>
<option value='<?=$rowtybook['value']?>'><? =$rowtybook['name']?></option>
<? } ?>
and html
<select id='book' name='book'>
<? $result = mysql_query("SELECT * FROM store WHERE status = 1");
while($row = mysql_fetch_assoc($result)){
?>
<option value='<?=$row['value']?>'><?=$row['name']?></option>
<?
}
?>
thanks in advance.
You have not printed any thing in book.php that is why it's give you the blank response
$dtacc = $_GET['cc'];
$tybook = "SELECT * FROM store
WHERE status = '1'
AND parentid ='".$dtacc."' ";
$pretybook = mysql_query($tybook) or die(mysql_error());
$infor = null;
while($rowtybook = mysql_fetch_array($pretybook)){
$infor['name'] = $rowtybook['name'];
$infor['value'] = $rowtybook['value'];
$data[] = $infor;
}
die(json_encode($data));

Categories