dongzouban9871 2018-07-12 08:00
浏览 155
已采纳

显示文本框多行值

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);
        }
      }
    });
  });
});
  • 写回答

4条回答 默认 最新

  • douxia2137 2018-07-12 08:15
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?