Display textbox multiple row values - javascript

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);
}

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...

text/string drop-down values cannot be filled

I am wondered why its happening.
Actually, I am using dropdown based textbox selection.
whenever my drop-down option value I am using numbers then textbox filled properly based on my drop-down selection.
Although I am using my dropdown value text/string then textbox values cannot be filled when I change my drop-down selection.
I want drop-down option value text/string then textbox value filled.pls, help a lot.
Working Code:-
<select id="sel_depart">
<option value="0">- Select -</option>
<option value="1">too</option>
<option value="2">Stencil</option>
</select>
<input id="sel_user" size="">
Jquery
<script type="text/javascript">
$(document).ready(function(){
$("#sel_depart").change(function(){
var deptid = $(this).val();
$.ajax({
url: 'getUsers2.php',
type: 'post',
data: {depart:deptid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#sel_user").empty();
for( var i = 0; i<len; i++){
var id1234 = response[i]['id123'];
//var name1234 = response[i]['name123'].children('option:selected').text();
var name1234 = response[i]['name123'];
// $("#sel_user").append("<option value='"+id+"'>"+name+"</option>");
// var value = $(this).children('option:selected').text();
$("#sel_user").val(name1234);
// $("#sel_user").val(value);
// $.isNumeric($("#sel_user").val(name1234));
}
}
});
});
});
</script>
getUsers2.php
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "boti_leave_info"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$departid = $_POST['depart']; // department id
$sql = "SELECT ID,Mobile FROM user_content WHERE Category=".$departid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['ID'];
$name = $row['Mobile'];
$users_arr[] = array("id123" => $userid, "name123" => $name);
}
// encoding array to json format
echo json_encode($users_arr);
?>
The same code is not working when i just change my <option value="too">too</option> instead of <option value="1">too</option>
listen for the change event on the sel_depart and set the value of the input accordingly :
$(document).ready(function(){
$('#sel_depart').on('change', function(){
//var value = $(this).val(); // uncomment this line to get the value (0, 1, 2 ... )
var value = $(this).children('option:selected').text();
$('#sel_user').val( value );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel_depart">
<option value="0">- Select -</option>
<option value="1">too</option>
<option value="2">Stencil</option>
</select>
<input id="sel_user" size="">

How to filter data using an input box and dropdown menus

Hey So I have an issue with my code where I am trying to filter the data coming from the database and display it in a table. I am using AJAX to send the request to the PHP page. I have not had any luck in searching for a solution. (It will be similar to your common real estate website, or retail, etc. where the user can input a location in the search box, search for it, and then filter the displayed data using the 2 dropdown menus).
My index.php page has 3 inputs (a textbox and 2 dropdowns)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off">
<div id="here"></div>
<select class="orderType" name="type" id="orderByType" data-toggle="dropdown" onchange="displaySelection(this.value)">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" id="orderBy" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable">
Then my ajax calls on the index.php page (The AJAX will be another question later, as I'm sure there is a better way than what I have, to send the data)
function fill(Value)
{
$('#search').val(Value);
$('#here').hide();
}
$(document).ready(function(){
$("#search").keyup(function(){
var x = $('#search').val();
if(x==""){
$("#here").html("");
$('#searchTable').html("");
}
else{
$.ajax({
type:'POST',
url:'test.php',
data:'q='+x,
success:function(html){
$("#here").html(html).show();
}
});
}
});
$('.searchForm').change(function(){
var type = $('#search').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { search : type, city : city },
success: function(response){
$("#searchTable").html(response);
$('#search').live("keypress",function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
e.stopPropagation();
$('#searchTable').show();
}
});
}
});
});
$('.orderClass').change(function(){
var order = $('#orderBy').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderBy : order, city : city },
success: function(response){
$("#searchTable").html(response);
}
});
});
$('.orderType').change(function(){
var type = $('#orderByType').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderByType : type, city : city},
success: function(response){
$("#searchTable").html(response);
}
});
});
});
And then on test.php
(I can filter the data with the 2 dropdown menus and that will work fine, but i'm not sure how to filter the data that is displayed from the search input box.)
$stmt = "SELECT * FROM places";
if(isset($_POST['search'])){
$search = htmlspecialchars($_POST['search']);
$stmt .= " WHERE name = :search";
}
if(isset($_POST['orderByType'])){
$selection = $_POST['orderByType'];
$stmt .= " AND type = :selection";
}
if(isset($_POST['orderBy'])){
$order = $_POST['orderBy'];
$selection = $_SESSION['id'];
$stmt .= " ORDER BY".$order;
}
$stmt = $conn->prepare($stmt);
$search = "%".$search."%";
$stmt->bindValue(':search', $search, PDO::PARAM_STR);
$stmt->bindParam(":selection", $selection);
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo $row['data'];
}
}
//Search input live search
if(!empty($_POST['q'])){
$name = $_POST['q'];
$name = htmlspecialchars($name);
$liveSearch = $conn->prepare("SELECT name, city FROM places WHERE name LIKE :name OR city LIKE :name");
$name = "%".$name."%";
$liveSearch->bindValue(':name', $name, PDO::PARAM_STR);
$result = $liveSearch->fetchAll();
if($liveSearch->rowCount() > 0){
foreach($result as $row){
echo $row['name'];
}
}
else{
echo "No results found";
}
}
(If there is a great system in place that can search using user input and then filter it using dropdown menus, then please let me know)
Thanks in advance.
If I was going to do this, I would probably make an ajax object for reuse reasons and a php object to handle queries:
/defines.php
You may or may not have defines for your db credentials. I use these in the class below.
define("DB_USER",'root');
define("DB_PASS",'password');
define("DB_HOST",'localhost');
define("DB_NAME",'dbname');
/classes/Query.php
This is a stripped-down query engine which makes basic queries. I use it to save on rewriting a bunch of prepares and executes, but you can do whatever you like there.
class Query
{
private static $singleton,
$con;
private $rquery,
$bind;
public function __construct()
{
if(self::$singleton instanceof Query)
return self::$singleton;
self::$singleton = $this;
}
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
return self::$con;
}
public function query($sql,$bind = false)
{
$this->bind = false;
try {
if(empty($bind)) {
$this->rquery = $this->connect()->query($sql);
}
else {
foreach($bind as $key => $value) {
$bkey = ":{$key}";
$this->bind[$bkey] = $value;
}
$this->rquery = $this->connect()->prepare($sql);
$this->rquery->execute($this->bind);
}
}
catch (PDOException $e){
die('An application error occurred.');
}
return $this;
}
public function getResults()
{
while($results = $this->rquery->fetch(PDO::FETCH_ASSOC)) {
$row[] = $results;
}
return (!empty($row))? $row : 0;
}
}
/functions/searchPlaces.php
function searchPlaces($search,$type = false,$orderby = false)
{
$sVal = "%".$search."%";
array();
$sql[] = 'SELECT * FROM places WHERE `name` LIKE :0 or `city` LIKE :1';
$bind = array_fill(0,2,$sVal);
if(!empty($type)) {
$bind[] = $type;
$sql[] = 'AND `type` = :2';
}
if(!empty($orderby)) {
$order = ($orderby == 'lowest')? 'ASC' : 'DESC';
$sql[] = "order by `ID` {$order}";
}
// Here is where I use the query to send back results from DB
// you can just use a regular prepare/bind/execute if you like
$qEngine = new Query();
return $qEngine->query(implode(' ',$sql),$bind)->getResults();
}
/test.php
<?php
// Put our db credentials
require_once(__DIR__.'/defines.php');
if(!empty($_POST)) {
// Needs the search function and the query class
// (disregard class if you don't use it)
require_once(__DIR__.'/functions/searchPlaces.php');
require_once(__DIR__.'/classes/Query.php');
// I am just sending an array back, but you can format it as you please
print_r(searchPlaces($_POST['search'],$_POST['type'],$_POST['order']));
exit;
}
/index.php
<script>
// I like to make an ajax engine, it saves on rewriting all the same stuff
// on later ajax calls
var AjaxEngine = function($)
{
this.send = function(data,func)
{
$.ajax({
url: '/test.php',
data: data,
type: 'post',
success: function(response){
func(response);
}
});
return this;
};
}
// You only need one document ready
$(document).ready(function(){
// Make an ajax engine
var Ajax = new AjaxEngine($);
// If form changes or key up in text field
$('.searchForm,.ajaxer>select').on('keyup change',function(e) {
e.preventDefault();
// Serialize the form
var formData = $('.ajaxer').serialize();
// Send the ajax and return results
Ajax.send(formData,function(response) {
$('#searchTable').html(response);
});
});
});
</script>
<!-- Note changes to the form for classes and ids -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="ajaxer">
<input name="search" type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off" />
<div id="here"></div>
<select class="orderType" name="type" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable"></div>

Array of drop down list in html

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>

Categories