首页 \ 问答 \ jquery根据第一个菜单中的选项填充第二个菜单(jquery populate second menu based on option in first menu)

jquery根据第一个菜单中的选项填充第二个菜单(jquery populate second menu based on option in first menu)

我确信这已被多次询问和回答,但我找不到合适的解决方案。 我想根据第一个菜单中的选择填充第二个菜单:

<form id="form1" name="form1" method="post" action="">
  <select name="sub_discipline" id="sub_discipline">
    <option>Select Sub-discipline...</option>
    <?php 
$query = mysql_query("SELECT * from sub_discipline ORDER BY name ASC");
for($i=0;$i<mysql_num_rows($query);$i++) {
$row=mysql_fetch_assoc($query);
?>
    <option value="<?php echo $row['sub_discipline_pk']; ?>"><?php echo $row['name']; ?></option>
    <?php 
}
?>
  </select>
  <select name="topic_place" id="topic_place">
    <option>Select Topic...</option>
  </select>
</form>

我有以下js:

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">

$(function() {
    $(':input[name=sub_discipline]').change(function(e) {
        $.get(
            'get_topics.php',
            {'sub_discipline_pk':$(this).val()},
            function(data) {
                $(':input[name=topic_place]').html( data );
            },
            'html'
          );
    }).change();
});​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

</script>

get_topics.php有

$sub_discipline_pk = $_GET['sub_discipline_pk'];

$query = "SELECT * FROM topic WHERE sub_discipline_fk = '$sub_discipline_pk'";
$result = mysql_query($query, $connection) or die(mysql_error());

while ($row = mysql_fetch_array($result)) { ?>
   <option value="<?php echo $row['topic_pk']; ?>">
   <?php echo $row['title']; ?></option>
   <?php } 
   ?> 

get_topics.php返回:

<option value="1">
   Topic 1</option>
      <option value="2">
   Topic 2</option>

所以上面应该工作......

谢谢你的帮助!!


I'm sure this has been asked and answered many times, but I can't find a working solution. I want the second menu to populate based on a selection in the first menu:

<form id="form1" name="form1" method="post" action="">
  <select name="sub_discipline" id="sub_discipline">
    <option>Select Sub-discipline...</option>
    <?php 
$query = mysql_query("SELECT * from sub_discipline ORDER BY name ASC");
for($i=0;$i<mysql_num_rows($query);$i++) {
$row=mysql_fetch_assoc($query);
?>
    <option value="<?php echo $row['sub_discipline_pk']; ?>"><?php echo $row['name']; ?></option>
    <?php 
}
?>
  </select>
  <select name="topic_place" id="topic_place">
    <option>Select Topic...</option>
  </select>
</form>

I have the following js:

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">

$(function() {
    $(':input[name=sub_discipline]').change(function(e) {
        $.get(
            'get_topics.php',
            {'sub_discipline_pk':$(this).val()},
            function(data) {
                $(':input[name=topic_place]').html( data );
            },
            'html'
          );
    }).change();
});​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

</script>

get_topics.php has

$sub_discipline_pk = $_GET['sub_discipline_pk'];

$query = "SELECT * FROM topic WHERE sub_discipline_fk = '$sub_discipline_pk'";
$result = mysql_query($query, $connection) or die(mysql_error());

while ($row = mysql_fetch_array($result)) { ?>
   <option value="<?php echo $row['topic_pk']; ?>">
   <?php echo $row['title']; ?></option>
   <?php } 
   ?> 

get_topics.php returns:

<option value="1">
   Topic 1</option>
      <option value="2">
   Topic 2</option>

So the above SHOULD work...

Thanks for any help!!


原文:https://stackoverflow.com/questions/14315465
更新时间:2019-12-03 08:12

最满意答案

我决定采用ajax解决方案:

<script type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
        var xmlhttp=false;  
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {       
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
    }



    function getTopics(strURL) {        

        var req = getXMLHTTP();

        if (req) {

            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('topics').innerHTML=req.responseText;                       
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }

    }
</script>

形成:

<form id="form1" name="form1" method="post" action="">
  <table width="61%" border="0">
    <tr>
      <td width="16%">Sub-discipline</td>
      <td colspan="2"><select name="sub_discipline" id="sub_discipline" onChange="getTopics('get_topics.php?sub_discipline_pk='+this.value)">>
                  <option>Select Sub-discipline...</option>
                  <?php 
$query = mysql_query("SELECT * from sub_discipline ORDER BY name ASC");
for($i=0;$i<mysql_num_rows($query);$i++) {
$row=mysql_fetch_assoc($query);
?>
                  <option value="<?php echo $row['sub_discipline_pk']; ?>"><?php echo $row['name']; ?></option>
                  <?php 
}
?>
              </select></td>
    </tr>
    <tr>
      <td>Title</td>
      <td colspan="2"><input name="title" type="text" id="title" size="45" maxlength="100" /></td>
    </tr>
    <tr>
      <td>Topic</td>
      <td colspan="2"><textarea name="topic" id="topic" cols="45" rows="5"></textarea></td>
    </tr>
    <tr>
      <td>Placement</td>
      <td width="22%"><p>
        <label>
          <input type="radio" name="order" value="before" id="order_0" />
          Before</label>

        <label>
          <input type="radio" name="order" value="after" id="order_1" />
          After</label>
        <br />
      </p></td>
      <td><div id="topics"></div></td>
    </tr>
    <tr>
      <td>Available to Program</td>
      <td colspan="2">&nbsp;</td>
    </tr>
  </table>
</form>

get_topics.php:

<?php
require_once('../connection/connect.php');
mysql_select_db($database, $connection);

$sub_discipline_pk = $_GET['sub_discipline_pk'];

$query = "SELECT * FROM topic WHERE sub_discipline_fk = '$sub_discipline_pk'";
$result = mysql_query($query, $connection) or die(mysql_error());

?>
<select name="topic">
<option>Select a topic...</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['topic_pk']; ?>"><?php echo $row['title']?></option>
<?php } ?>
</select>

I decided to just go with the ajax solution:

<script type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
        var xmlhttp=false;  
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {       
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
    }



    function getTopics(strURL) {        

        var req = getXMLHTTP();

        if (req) {

            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('topics').innerHTML=req.responseText;                       
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }

    }
</script>

Form:

<form id="form1" name="form1" method="post" action="">
  <table width="61%" border="0">
    <tr>
      <td width="16%">Sub-discipline</td>
      <td colspan="2"><select name="sub_discipline" id="sub_discipline" onChange="getTopics('get_topics.php?sub_discipline_pk='+this.value)">>
                  <option>Select Sub-discipline...</option>
                  <?php 
$query = mysql_query("SELECT * from sub_discipline ORDER BY name ASC");
for($i=0;$i<mysql_num_rows($query);$i++) {
$row=mysql_fetch_assoc($query);
?>
                  <option value="<?php echo $row['sub_discipline_pk']; ?>"><?php echo $row['name']; ?></option>
                  <?php 
}
?>
              </select></td>
    </tr>
    <tr>
      <td>Title</td>
      <td colspan="2"><input name="title" type="text" id="title" size="45" maxlength="100" /></td>
    </tr>
    <tr>
      <td>Topic</td>
      <td colspan="2"><textarea name="topic" id="topic" cols="45" rows="5"></textarea></td>
    </tr>
    <tr>
      <td>Placement</td>
      <td width="22%"><p>
        <label>
          <input type="radio" name="order" value="before" id="order_0" />
          Before</label>

        <label>
          <input type="radio" name="order" value="after" id="order_1" />
          After</label>
        <br />
      </p></td>
      <td><div id="topics"></div></td>
    </tr>
    <tr>
      <td>Available to Program</td>
      <td colspan="2">&nbsp;</td>
    </tr>
  </table>
</form>

get_topics.php:

<?php
require_once('../connection/connect.php');
mysql_select_db($database, $connection);

$sub_discipline_pk = $_GET['sub_discipline_pk'];

$query = "SELECT * FROM topic WHERE sub_discipline_fk = '$sub_discipline_pk'";
$result = mysql_query($query, $connection) or die(mysql_error());

?>
<select name="topic">
<option>Select a topic...</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['topic_pk']; ?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
2013-12-23

相关问答

更多

AngularJS在ng-repeat内部工作中重新渲染(AngularJS re-rendering in ng-repeat inner working)

函数循环返回ngRepeat正在跟踪的新对象。 因此,当ng-repeat循环变量的值发生变化时,它会触发新的渲染。 ngRepeat跟踪集合中的所有项及其相应的DOM元素。 因此,如果该项目已存在,则不会重新渲染。 The function loop returns a new object which ngRepeat was tracking. So when the value of ng-repeat loop variable changes, it triggers the new

格式化第一篇与foreach之后的数据爆炸(format explode data after first piece with foreach)

尝试这个: $array = explode(",", $l); echo implode(" OR ", $array); 或者在一个班轮中: echo implode(" OR ", explode(",", $l)); try this: $array = explode(",", $l); echo implode(" OR ", $array); Or in one liner: echo implode(" OR ", explode(",", $l));

AngularJs Directive元素的子元素为空(AngularJs Directive element children gives empty)

使用ng-model更好: var myapp = angular.module('myapp', []); myapp.controller('myCtrl', function($scope) { $scope.investments = [ {"name": "AARP Operating Funds"}, {"name": "Some Big Title"}, {"name": "I hatez IE8"}, {

在Forloop中更改变量(Changing a variable in Forloop)

你会想要使用数组: String[] serieses = { "Luggage Lost", "Customer Missing", "Recovered", "Forever Lost" }; // column keys... String[] months = { "January", "February", "March", "April", "May", "June", "July",

XML反序列化后返回单个节点(Single node returned after XML deserialization)

我刚试过以下代码: var file = new FileStream("Input.txt", FileMode.Open); var serializer = new XmlSerializer(typeof(Data)); var item = (Data)serializer.Deserialize(file); 使用您的输入XML数据和以下Class类声明: [Serializable] public class Class { [XmlElement("subj_area

如何在Audiokit上建立一个频率/音高信号的振荡器?(How to build an oscillator with an envelope on its frequency/pitch in Audiokit?)

似乎这太复杂或完全错误的方向。 我停止了这个approch并继续这个 。 Seems that this would be too complicated or the complete wrong direction. I stopped this approch and went on with this one.

Ruby FFI Enum用法 - 发送整数(Ruby FFI Enum usage - sending integer)

两次调用都会将整数2发送给函数。 第一个调用将解析符号:monday到2 ,第二个调用不需要,因为已经给出了2。 Both calls will send the integer 2 to the function. The first call will resolve the symbol :monday to 2, the second one doesn't need to because the 2 was already given.

如何使用Pyspark将数据框保存到pickle文件(How to save dataframe to pickle file using Pyspark)

saveAsPickleFile是RDD一种方法,而不是数据帧的方法。 请参阅此文档: http : //spark.apache.org/docs/latest/api/python/pyspark.html?highlight = pickle 所以你可以打电话: df.rdd.saveAsPickleFile(filename) 要从文件加载它,请运行: pickleRdd = sc.pickleFile(filename).collect() df2 = spark.createDat

相关文章

更多

最新问答

更多
  • 根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)
  • 分开foreach项目并单独打印(Separate foreach items and print them individually)
  • 写模式管道是否同步?(Is write mode pipe synchronous?)
  • 发现可用的Windows Phone强调色和本地化名称(Discover available Windows Phone accent colors and localized names)
  • 使用多线程和WPF更新集合(Update Collection with multithreading and WPF)
  • 如何在字符串的情况下使用同步?(How should the synchronization be used in case of strings?)
  • 打印唯一的行,比较不超过N个字符(Print unique lines, compare no more than N characters)
  • Javascript / jQuery - 如何调用switch case从另一个函数执行(Javascript/jQuery - how to call a switch case to execute from another function)
  • Hbase超时错误不断发生(Hbase timeout errors keep occuring)
  • 如何在Delphi中更改TabControl中活动TAB的颜色(How to change the color of active TAB in a TabControl, in Delphi)
  • 正则表达式:在sublime文本中替换一些PHP代码(Regex: replace some pieces of php code in sublime text)
  • 在带有Scene2D的LibGDX中,如何在按下按钮时连续向右走?(In LibGDX with Scene2D, how can I continuously walk to the right when a button is pressed?)
  • 累加器如何在Haskell中工作?(How do accumulators work in Haskell?)
  • 使用开关检查市场和前缀与正确的货币符号(using switch to check market and prefix with correct currency symbol)
  • 在哪里分配一次使用类?(Where to allocate one time use class?)
  • 如何从两个DateTime / NaiveDateTime获取持续时间?(How do I get Duration from two DateTime / NaiveDateTime?)
  • 解析TimeSpan大于24小时?(Parse a TimeSpan greater than 24 hours? [duplicate])
  • 如何在球拍中本地更改阅读规则?(How to locally change reading rules in racket?)
  • 数据库应该由DI注入时的模拟存储(通过构造函数)(Mock storage when database should be injected by DI (through constructor))
  • 使用maven集成2个eclipse项目(Integrate 2 eclipse projects using maven)
  • 角度ng-repeat不检测变化(Angular ng-repeat not detecting changes)
  • Xaml组件在Silverlight + XNA应用程序的多个页面中可见(Xaml component visible in multiple pages in Silverlight+XNA applications)
  • 如何将`var`变量等同于另一个查询(How to equate `var` variable to another query)
  • 如何设计hyperledger链代码以适合您的业务?(how to design your chaincode of hyperledger to fit for your business?)
  • PHP readfile错误(PHP readfile error)
  • 在Date之后排序列表然后是时间(Sorting list after Date then time)
  • Android内部版本号(Android build number)
  • 在没有预设退出条件的情况下停止无限循环(stopping an infinite loop with no preset exit condition)
  • Phonegap应用程序全屏通过html页面中的按钮(Phonegap Application fullscreen through a button in html page)
  • PAA是否适合在门户网站中自动执行wcm库部署和设置?(Is PAA a good candidate for automating wcm library deployment and setup in portal?)