我想使用javascript或jquery更改内容

时间:2012-11-04 18:19:54

标签: javascript jquery ajax html5 html-select

选择课程

<select>
    <option value="b.a">B.A</option>
    <option value="b.com">B.Com</option>
    <option value="b.b.a">B.B.A</option>
</select> 

选择学期

<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>

现在我想要的是当我选择第一道菜时,b.a。那就不要。学期中只有一个在“选择学期”列表中显示,而对于b.com,这些shud是2和forr b.b.a这些shud是3,即。一旦选择了课程页面shud自动刷新,学期的数量根据所选主题的变化而变化,关于我如何使用js或jquery或ajax实现这一点,请通过提供一些示例或教程来帮助我。

2 个答案:

答案 0 :(得分:1)

使用jQuery和AJAX的示例

  

HTML

<select id="selPrimary">
    <option value="b.a">B.A</option>
    <option value="b.com">B.Com</option>
    <option value="b.b.a">B.B.A</option>
</select>
<select id="selSecondary"></select>
  

脚本

// jQuery doc.ready function
$(function() { // all "action" script goes in here
    // Selects primary "select tag" by ID and assigns change event
    $("#selPrimary").on("change", function(e) {
        // Empty the options that might exist 
        // (from last choice in primary) and prep 
        // secondary for new options
        $("#selSecondary").empty();
        // .post is jQuery short hand for .ajax(..."type=post"
        $.post("someFolder/someController.php", // this first param tells location of your php backend controller
            function(data) { // this is the function that acts if the post is "successful"
                $("#selSecondary").html(data); //  fills secondary select tag with our new options
            },
            "json"); // this last param tells how to return the data
    });
})
  

控制器(本例中为PHP)

$retValue = "";
//Get Post Variables. 
if (isset($_POST['selPrimary'])){
    $value = $_POST['selPrimary'];   
    switch($value) {
        case "b.a":
            $retValue = '<option value='1'>1st</option><option value='2'>2nd</option<option value='3'>3rd</option>';
            break;
        case "whatev":
            $retValue = '<option value='1'>1st</option><option value='2'>2nd</option<option value='3'>3rd</option>';
            break;
    }
}

echo json_encode($retValue); 

答案 1 :(得分:0)

你可以试试这个......

<script>
function changeSem(sub)
{
 if(sub == 'b.a')
 {
  document.getElementById('sem').innerHTML = "<select id='semnum'>
<option value='1'>1st</option>
</select>";
 }
 if(sub == 'b.com')
 {
    document.getElementById('sem').innerHTML = "<select id='semnum'>
<option value='1'>1st</option>
<option value='2'>2nd</option>
</select>";
 }
 if(sub == 'b.b.a')
 {
    document.getElementById('sem').innerHTML = "<select id='semnum'>
<option value='1'>1st</option>
<option value='2'>2nd</option>
<option value='3'>3rd</option>
</select>";
 }
}
</script>
Select Course
<select id="sub" onchange="changeSem(this.value);">
<option value="b.a">B.A</option>
<option value="b.com">B.Com</option>
<option value="b.b.a">B.B.A</option>
</select> 
Select Semester
<div id="sem"></div>
希望它有所帮助!