简体   繁体   English

如何使用Javascript或Jquery切换选择元素?

[英]How to use Javascript or Jquery to switch the select elements?

I don't know much about Javascript and Jquery, but I do have to use it on a HTML select tags. 我对Javascript和Jquery不太了解,但是我必须在HTML select标签上使用它。 I have two database tables, grouptypes and groups. 我有两个数据库表,组类型和组。 A grouptype can have multiple groups, but a group only belongs to one grouptype. 一个组类型可以有多个组,但是一个组只能属于一个组类型。 I have two select tags, one is grouptypes and another one is groups. 我有两个选择标记,一个是组类型,另一个是组。 What I want to do is that whenever a user select a grouptype in the grouptypes dropdown menu, it triggers a handler to retrieve the corresponding groups that belong to that grouptype. 我想做的是,每当用户在grouptypes下拉菜单中选择一个grouptype时,它都会触发一个处理程序以检索属于该grouptype的相应组。 I need javascript or Jquery to get it done, but I am not able to write it myself. 我需要javascript或Jquery才能完成它,但是我自己不能写。 So anyone can help me? 有人可以帮助我吗? I would so appreciate it. 我会很感激。

 GroupType: <select name="groupType">

    <?php foreach($grouptypes as $type) : ?>

    <?php echo "<option value='" . $type['name'] . "'>" .$type['name']. "</option>"; ?>

    <?php endforeach ?>

  </select><br />


  Group: <select name="groups">

    <?php foreach($groups as $group) : ?>

    <?php echo "<option value='" . $group['name'] . "'>" .$group['name']. "</option>"; ?>

    <?php endforeach ?>

  </select><br />


  <?php 
    $query = "SELECT id, name FROM group_type";

    $grouptypes = $_db->getResultsForquery($query);


    $query = "SELECT id, name FROM groups";

    $groups = $_db->getResultsForquery($query);


  ?>

Here's what I would do. 这就是我要做的。 It uses jquery to send a get to a page called groups.php which will return some html you can parse. 它使用jquery将get发送到名为groups.php的页面,该页面将返回一些您可以解析的html。 Then you parse it :) 然后你解析它:)

$('#grouptype-select').change(function(){  //.change will detect when the select has been changed (an -option- has been chosen)
    var grouptype = $(this).val();   //create a variable from the -option- chosen
    $.get('groups.php', 'grouptype=' + grouptype, function(response){    //use jquery to send -get- to groups.php
        $('#list-of-groups').html(response);    //insert response into ur doc
    }
});

Something like http://www.yoursite.com?grouptype=abc will be sent using get asynchronously (ajax) Good luck! http://www.yoursite.com?grouptype=abc这样的内容将通过异步get (ajax)发送祝您好运!

PS Here is a jsfiddle to get you tinkering: http://jsfiddle.net/yLyTw/1/ PS这是一个让您修补的jsfiddle: http : //jsfiddle.net/yLyTw/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM