I have one drop-down box and one textbox. based on my drop-down selection textbox retrieve along with DB value. actually, its working fine without any issues. But my problem was database has two or more textbox values in particular drop-down selection. so I want to if multiple textbox values come to the same drop-down selection then it will display all values in textbox separated by the comma (,). Any help greatly appreciated.
Here is my used code for your reference:-
<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">
Jquery:-
<script 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 id1234 = response[i]['id123'];
var name1234 = response[i]['name123'];
$("#pnum").val(name1234);
}
}
});
});
});
</script>
Ajax Page:-
<?php
include('config.php');
// Check connection
if (!$db) {
die("Connection failed: " . mysqli_connect_error());
}
$departid = $_POST['depart'];
$sql = "SELECT Emp_Id,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);
}
echo json_encode($users_arr);
?>
My Sample Data:-
Category Mobile_Number
IT 9629292929
IT 8888888888
IT 5623566666
If I select the drop-down category "IT" then I want my textbox Mobile_Number output looks like this:-
9629292929,8888888888,5623566666
You can simply loop over json_encode()
d array.
And the join/implode the array values in a string combined by comma using PHP's in built function implode()
$arr = json_decode($yourArray);
$mobiles = array();
if (! empty($arr)) {
foreach ($arr as $elem) {
$mobiles[] = $elem['Mobile_Number'];
}
}
$mobileStr = ! empty($mobiles) ? implode(',', $mobiles) : '';
Now, use this $mobileStr
as value="$mobileStr"
in your text box.
You may use join function of javascript. Please refer following post. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_join
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.