Javascript表单选择更改选项动态列表

时间:2017-04-03 14:25:23

标签: javascript php html mysql ajax

我的项目现在有两个下拉菜单。一个是颜色,另一个是那种颜色的成员。目标是使用JS,所以如果我选择“红色”,只有红色的成员出现在第二个下拉列表中。我有我的SQL表和我的脚本。我不知道从哪里开始所以一些帮助会很好。

SQL:

+--------+--------------+
| Color  | MemberName   |
+--------+--------------+
| Red    | Joe Bob      |
| Red    | Catherine    |
| Blue   | Tommy        |
| Orange | John Razks   |
| Black  | Trevor Smith |
+--------+--------------+

+--------+
| Color  |
+--------+
| Red    |
| Blue   |
| Orange |
| Black  |
+--------+

PHP代码:

<!DOCTYPE html>
<html>
<head>
	<title>Test Page</title>
	<script src="jquery.js"></script>
</head>

<body>
<?php
function load_Color(){
	$conn=mysqli_connect("#variable");
	if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
	else{
	$output='';
	$sql = "SELECT * from Color order by Color ASC";
	$result = mysqli_query($conn, $sql);
	while($row=mysqli_fetch_array($result)){
		$output .= '<option value="'.$row["Color"].'">'.$row["Color"].'</option>';
	}
	return $output;
	}
}
?>
<div class="formatbody" id="formatbody">
			<div class="category_div" id="category_div">Color:
				<select id="color" name="color">
					<option value="">Select Color</option>
						<?php echo load_Color(); ?>
				</select>	
			</div>	
			<div class="sub_category_div" id="sub_category_div">Individual: 
				<select name="individual" id="individual">
					<option value="">Select Individual</option>
				</select>
			</div>
</div>
</body>
</html>

<script>
$(document).ready(function(){
	$('#color').change(function(){
		var Color = $(this).val();
		$.ajax({
			url: "fetch.php",
			method: "POST",
			data:{color: Color},
			dataType: "text",
			success: function(data)
			{
				$('#individual').html(data);
			}
		});
	});
});
</script>

Fetch.PHP:

<html>
<body>
<?php
	$conn=mysqli_connect("#Variable");
	if(!$conn){ die("Connection Failed".mysqli_connect_error()); }
	else{
	$output='';
	$sql = "SELECT MemberName from Members where Color = '".$_POST["color"]."' ORDER BY MemberName ASC";
	$result = mysqli_query($conn, $sql);
	$output = '<option value="">Select the Individual</option>';
	while ($row=mysqli_fetch_array($result))
	{
		$output .='<option value="'.$row["MemberName"].'">'.$row["MemberName"].'</option>';
	}
	}
	
	
	echo $output;
	?>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您需要按照以下步骤操作,例如:

HTML:

<select name="color">
    <option value="red">red</option>
    <option value="blue">blue</option>
    <option value="green">green</option>
</select>

<select name="individuals"></select>

JS:

<script>
    $('select[name="color"]').change(function(){
        var selectedColor = $(this).val();

        $.ajax({
            url: 'url-to-filter-individuals.php',
            method: 'post',
            data: {color:selectedColor},
            dataType: 'json',
            success: function(response){
                if(response['status']==='success'){

                    var html = '';

                    for(var i=0; i<response['data'].length; i++){
                        html += '<option value="'+response['data'][i]['id']+'">'+response['data'][i]['name']+'</option>';
                    }

                    $('select[name="individuals"]').after(html);
                }
            }
        });
    });
</script>

url-to-filter-persons.php:

<?php
if(!empty($_POST['color'])){

    $color = $_POST['color'];

    // suppose I have connection to db in $con variable

    $stmt = $con->prepare("SELECT * FROM individuals_table iTable WHERE iTable.color LIKE ?");

    if($stmt){

        $stmt->bind_param('s',$color);

        if($stmt->execute()){

            /* Get the result */
           $result = $stmt->get_result();

           /* Get the number of rows */
           $num_of_rows = $result->num_rows;

           if($num_of_rows > 0){

                $data = array();

                while ($row = $result->fetch_assoc()) {
                    $data[] = array('id'=>$row['id'],'name'=>$row['name']);
               }

               /* free results */
               $stmt->free_result();

               /* close statement */
               $stmt->close();

               echo json_encode(array('status'=>'success','data'=>$data));
               exit(0);
           }
        }
    }
}
echo json_encode(array('status'=>'failure'));
exit(0);

答案 1 :(得分:0)

您只需将数据存储在javascript对象中即可。然后,您可以访问它并动态创建列表

HTML:

    <body>
    <form id="blah">
        Color:
        <select id="committee" name="committee" onchange="committeeSelected(this.value);">
            <option value="">Select Color</option>
            <option value="Red">RED</option>
            <option value="Blue">BLUE</option>
            <option value="Black">BLACK</option>
            <option value="Orange">ORANGE</option>
        </select>

        <div class="sub_category_div" id="sub_category_div">
        Individual: 
        <select name="senator" id="senator">
        </select>
        </div>
  </form>
</body>

的javascript:

<script type="text/javascript">
    var data = 
    {
        "Red":[
            "Joe Bob",
            "Catherine"
        ], 
        "Blue":[
            "Tommy"
        ],
        "Black":[
            "Trevor Smith"
        ],
        "Orange":[
            "John Razks"
        ]
    };

    var colors = [ "Red", "Blue", "Black", "Orange"];

    function committeeSelected(selected){       
        // get placeholder
        var senator = document.getElementById("senator");

        // first clear everything
        while(senator.firstChild)
        {
            senator.removeChild(senator.firstChild);
        }

        // first node is always select individual
        createOption("Select Individual");

        // here we need to generate listbox
        for(i=0; i<data[selected].length;i++)
        {
            var a = data[selected][i];

            createOption(a);
        }
    }

    function createOption(value){
            // attribute storing color value
            c = document.createAttribute("value");
            c.value=value;

            // textnode for storing color value
            cText = document.createTextNode(value);

            // append attribute node
            option = document.createElement("option");
            option.setAttributeNode(c);

            option.appendChild(cText);

            // append child
            senator.appendChild(option);
    }
</script>