如何在选择特定单选按钮时调用javascript?

时间:2013-07-16 15:30:34

标签: php javascript html

<div id="dept-or-user-div" class="panel" style="padding-bottom:10px;">
    <h3 class="div-title">Select Alert Recipients</h3>
     <div class="recipient-error" style="display:none;"><p style="padding-top:10px; color:#f00;">Please select at least one recipient</p></div>

    <p>
        <input type="radio"  checked value="dept" name="user-or-dept">Department</input>
        <input type="radio"  value="user" name="user-or-dept">User</input>
        <input type="radio"  value="both" name="user-or-dept">Both</input>
    </p>
    <div class="department-select" class="dept">
        <p><label for="department-choice">Department:</label>
         <select name="department-choice" id="department-choice">
            <option></option>
            <?php
                echo get_departments();
            ?>
        </select></p>
    </div><!--end #department-select-->
    <div class="user-select user" >
        <p><label for="user-choice">User:</label> 

        <select name='user-choice' id="user-choice">
            <option></option>
            <?php
                echo get_users('option');
            ?>
        </select></p>

    </div><!--end #user-select--> 

</div><!--end #dept-or-user-div-->

这里我有三个单选按钮

  1. 部门(部门下拉)
  2. 用户(用户下拉列表)
  3. 两者(用户和部门dropwon)
  4. 当我选择了值为“Both”的单选按钮,即第三个单选按钮时,我想要这样做,我想调用js函数并根据部门值动态填充用户下拉列表。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

给它一个id,

 <input type="radio"  id="both" value="both" name="user-or-dept">Both</input>

然后,使用Jquery ....做这样的事情......

 $('input#both').change(function(){

 if($(this).is(':checked')) {

 //do your ajax call here to retrieve values from database based on whatever criteria
 //and populate the result wherever you want
 $.ajax({
 url: "getdept.php",
 type: "POST",
 data: {type: "both"},
 dataType: "html",
 success: function(result){
  $('#department-choice').html(result);
 }
 }); 

}}

然后在那个php文件中,类似......

$both = mysql_real_escape_string($_POST['type']);

$sql = "SELECT * FROM table WHERE dept = $both";
//dunno what your query will be, because I have no idea of your database
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)){
  echo "<option>".$row['dept']."</option>";
}

这将以......的形式输出。

 <option>blah blah</option>
 <option>blah blah</option>
 <option>blah blah</option>

将使用上面的ajax插入select下拉列表。