根据下拉选择填充复选框

时间:2016-11-18 02:21:03

标签: javascript php jquery ajax

在表单中,我确实有一个从db填充的行业列表。我想根据选定的行业填写一个复选框列表。

我尝试过以下但是没有用。 你能帮忙吗。我仍在学习编码,非常感谢你的帮助。

的index.php

// The dropdown is populated from DB
<select class="set_industry">
    <option value="1">Healthcare</option>
    <option value="2">Food & Beverage</option>
    <option value="3">Real Estate</option>
</select>
// Preferably the selection would produce var $ind_id
.
.
.
.
// I want the below to be executed based on the selection from above

<?php 
if(isset($_POST['id'])) {
  $ind_id = $_POST['id'];
  $x="SELECT * FROM srv_tbl WHERE ind_id=$ind_id";
  $res=query($x);

  while ($y=mysqli_fetch_array($res)) { ?>
  <div>
    <label>
      <input type="checkbox" value="<?php echo $y['srv_id'] ?>"> <?php echo $y['srv_name'] ?>
    </label>
  </div>
<?php } 
} ?>

<script>Link to js script</script>

的script.js

$(".set_industry").on('change', function(){ 
    var ind_id = $(this).attr("value");
    $.post("index.php", {id: ind_id}, function());  
});

1 个答案:

答案 0 :(得分:0)

分开您的PHP代码。

<强>的index.php

<?php 

if(isset($_POST['id'])) {

  $ind_id = $_POST['id'];
  $x="SELECT * FROM srv_tbl WHERE ind_id=$ind_id";
  $res=query($x);

  $returnString = '';   
  while ($y=mysqli_fetch_array($res)) {

     $returnString .= '<div><label><input type="checkbox" value=".$y['srv_id'].">.$y['srv_name'].</label></div>';
  }

  echo $returnString;
} ?>

将新div添加到HTML页面

<强>的index.html

<select class="set_industry">
    <option value="1">Healthcare</option>
    <option value="2">Food & Beverage</option>
    <option value="3">Real Estate</option>
</select>

<div id="response"></div>

<script>Link to js script</script>

script.js

进行这些更改
$(".set_industry").on('change', function(){ 
    var ind_id = $(this).attr("value");
    $.post("index.php", {id: ind_id}, function(data){

       $("#response").html( data );
    });  
});