从下拉列表中选择后自动填充文本框

时间:2018-08-15 06:27:11

标签: php mysql database

在我的html中,我使用了从数据库表中获取数据并将数据存储到另一个表中的标记。我的代码是:

       <select class="form-control" name="name" required> 
<option value="0">Please Select Hotel</option>
    <?php
        while($row = mysqli_fetch_assoc($get))
        {
        ?>
        <option value = "<?php echo($row['name'])?>" >
            <?php echo($row['name']) ?>
        </option>
        <?php

        }               
    ?>
</select>

我想在该选择选项下方添加一个文本填充,其中从下拉菜单中选择后数据将是数据库中的自动字段。我的代码是:

<input type="text" class="form-control" placeholder="username" name="username" value="<?php echo($row['username']) ?>" disabled required />

但是从提交后,自动填充文本框中没有存储数据

3 个答案:

答案 0 :(得分:1)

从标题“从下拉列表中选择后自动填充文本框”的标题开始,我认为您必须将所选选项的值放置在输入字段中。如果是这样,则需要使用JSjQuery

如果我是正确的,则可以检查以下代码:

// Pure JS

document.getElementById("selectname").onchange = function() {
  var e = document.getElementById("selectname");
  var strUser = e.options[e.selectedIndex].value;
  document.getElementById("username").value = strUser;
};

// jQuery

$('body').on('change', '#selectname', function() {
$('#username2').val($('#selectname option:selected').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="name" id="selectname">
  <option value="User 1">User 1</option>
  <option value="User 2">User 2</option>
  <option value="User 3">User 3</option>
  <option value="User 4">User 4</option>
  <option value="User 5">User 5</option>
</select>

<input type="text" class="form-control" placeholder="username" name="username" id="username" value="" disabled required />

<input type="text" class="form-control" placeholder="username" name="username2" id="username2" value="" disabled required />

有两个代码段,一个用于JS,另一个用于jQuery

答案 1 :(得分:0)

您必须注意以下内容:

<input type="textbox" name="Percentage" value="100" disabled /> 
<input type="textbox" name="Percentage" value="100" readonly/> 

只读

  1. 只读元素获得焦点,但用户无法对其进行修改。
  2. 标签导航中包含只读元素。
  3. 只读元素已成功发布。

已禁用

  1. 禁用的控件无法获得焦点。
  2. 在选项卡导航中跳过了禁用的控件。
  3. 无法成功发布禁用的控件。

=>因此,必须将“已禁用”更改为“只读”->提交表单后发送数据。

解决方案:

<input type="text" class="form-control" placeholder="username" name="username" value="<?php echo($row['username']) ?>" readonly required />

答案 2 :(得分:0)

请注意fromform的拼写,因为在代码中混合使用这两种代码都是无效的。

如果希望获取值,则将表单标签添加到选择/下拉框中。

   <form action="" method="POST">
    <select class="form-control" name="hotelName" required> 
      <option value="0">Please Select Hotel</option>
        <?php
            while($row = mysqli_fetch_assoc($get))
            {
                echo "<option value ='".$row['name']."'>".$row['name']."</option>";
            }               
        ?>
    </select>
   <form>

如果action=""被发送到另一个页面,则将其提交到同一页面,然后在该页面添加页面链接。

method="POST"提交带有post request的表单(如果您希望使用get request,然后将其更改为method="GET"

使用$_POST['hotelName']$_GET['hotelName']来抓住用户输入

还请记住始终对所有用户输入执行验证,并在其上使用bindParam,然后再将其保存到数据库中更好,仍然使用PDO

相关问题