Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Populating a second select box depending of the first select box option

I'm having this select, let's call it "X", that is populated with car brands as options from the database via a SELECT.

<select name="X">
<?php
$row = mysqli_query("SELECT * FROM brands");
while($row2 = mysqli_fetch_array($row))
echo '<option value="' . $row2['brandID'] . '">' . $row2['brandName'] . '</option>
?>
</select>

Now i have to populate the second select, called "Y", with the models specifics to a brand selected.

For example, if the option that's selected in the first select box (X) is Audi i should have as options in the second select (Y) the following: A4,A6,TT,TTs

To populate the second select box manually is easy, basicaly the same thing as for the first just with a different SQL request.

$row = mysqli_query("SELECT modelName from modele WHERE brandName = '$brand'");

Where $brand would have a value according to the first select's selection.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Put an id in your <select name="X"> code like <select name="X" id ="X">

Put another select like <select name="Y" id="Y">. Which will be blank.

put this jquery in your page.

$("X").on("change",function(){
    var x_value=$("X").val();
    $.ajax({
        url:'ajax.php',
        data:{brand:x_value},
        type: 'post',
        success : function(resp){
            $("#Y").html(resp);               
        },
        error : function(resp){}
    });
});

in your ajax.php add the query.

<?php
$row = mysqli_query("SELECT modelName from modele WHERE brandName =".$_POST['brand']);
while($row2 = mysqli_fetch_array($row))
    echo '<option value="' . $row2['modelId'] . '">' . $row2['modelName'] . '</option>
?>

Hopefully it will work. Please tell me if you need anything.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...