You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将department_tbl的ID值放入TextBox而非弹窗?PHP+MySQL+jQuery实现

Solution: Populate Textbox with Selected Department ID

Got it, let's get this sorted for you! We'll adjust your code to put the selected department ID directly into the textbox instead of showing an alert. Here's how to do it step by step:

Step 1: Add an ID to your textbox

First, give your text input a unique ID so jQuery can easily target it. Let's use departmentIdInput for this:

<input type="text" id="departmentIdInput" value="">

Step 2: Update the jQuery change event

Instead of using alert(), we'll use jQuery's .val() method to set the selected department ID into the textbox. Here's the modified script:

$(document).ready(function() {
  $("#departmentlvl").on('change', function () {
    // Grab the selected department ID
    const selectedDeptId = $(this).val();
    // Populate it into the textbox
    $("#departmentIdInput").val(selectedDeptId);
  });
});

Full Working Code

Here's the complete modified code with all changes applied:

<select name="departmentlvl" id="departmentlvl">
  <option value="" >Choose Department Level</option>
  <?php 
    $qry="Select * from department_tbl"; 
    $result=mysqli_query($conn,$qry); 
    while($row = mysqli_fetch_array($result)) {
      extract($row);
      echo "<option value='".$department_id."'>".$departmentDesc." </option>";
    } 
  ?>
</select>

<!-- Textbox to hold the selected department ID -->
<input type="text" id="departmentIdInput" value="">

<!-- Make sure you include jQuery (use local file or CDN) -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function() {
  $("#departmentlvl").on('change', function () {
    $("#departmentIdInput").val($(this).val());
  });
});
</script>

Quick Notes

  • The ID we added to the textbox lets jQuery know exactly where to put the selected value.
  • The change event now directly updates the textbox's content instead of triggering an alert.
  • Don't forget to include the jQuery library (either via CDN like the example, or a local file) otherwise the script won't run.

内容的提问来源于stack exchange,提问作者Cesar Wencester

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:35:09