创建后禁用选择框选项

x3naxklr  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(278)

我有一个从mysql数据库动态创建的选择框,然后我使用一个函数在索引[0]处添加一个“please select”选项,然后强制索引[0]成为选中的选项。我的问题是如何在创建索引[0]之后禁用它,或者在函数中创建索引的过程中禁用它。因此,归根结底,“请选择”选项不是一个有效的可选择选项。
提前谢谢你的建议。

<?php
 $con = mysqli_connect("localhost","root","","karaoke");

 // Check connection
 if (mysqli_connect_errno())
 {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $sql = "Select * FROM regulars ORDER BY Regulars ASC";
  $result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
  $opt = "<select id = 'regulars' name = 'regulars'>";

  while($row = mysqli_fetch_assoc($result)) {
      $opt .= "<option value'{$row['Regulars']}'>{$row['Regulars']}</option>\n";
   }
 $opt .="</select>"
 ?>

 <center><div>
 <?php
 echo $opt;
 ?>

 </div></center>

 <script>
  function myFunction() {
   var x = document.getElementById("regulars");
   var option = document.createElement("option");
   option.text = "Please Select";
   x.add(option, x[0]);
  }
  </script>

  <script>
  myFunction()
  document.getElementById("regulars").selectedIndex = "0";
  </script>
xmd2e60i

xmd2e60i1#

最简单的方法是用php做所有事情。不需要所有的js来添加这个选项。另外,它将是dom的一部分,以后更容易操作它(即删除禁用的)

<?php
 $con = mysqli_connect("localhost","root","","karaoke");

 // Check connection
 if (mysqli_connect_errno())
 {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  $sql = "Select * FROM regulars ORDER BY Regulars ASC";
  $result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
  $opt = "<select id = 'regulars' name = 'regulars'>";
  $opt .= "<option value=\"\" disabled>Please select...</option>";
  while($row = mysqli_fetch_assoc($result)) {
      $opt .= "<option value'{$row['Regulars']}'>{$row['Regulars']}</option>\n";
   }
 $opt .="</select>"
 ?>
zwghvu4y

zwghvu4y2#

只要设定 disabled 属性为 true 对于新创建的选项。

function myFunction() {
  var x = document.getElementById("regulars");
  var option = document.createElement("option");
  option.text = "Please Select";
  option.disabled = true;
  x.add(option, x[0]);
}

myFunction();
document.getElementById("regulars").selectedIndex = "0";
<select id="regulars">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

相关问题