如何根据第一个select
的值添加其他select
?
当第一个select
框发生更改时,我想根据第一个select
的值,发出一个AJAX请求来获取另一个select
的值,并将它们作为选项插入在DOM中的新select
中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<label>Country:</label>
<select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
<td id="response">
</td>
</tr>
</table>
</form>
</body>
</html>
&#13;
答案 0 :(得分:0)
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
//sample data - code starts here
var data = '[{"id":1,"name":"Karnataka"},{"id":2,"name":"Karnataka2"}, {"id":3,"name":"Karnataka3"}]';
data = jQuery.parseJSON( data );
//sample data ends here
$('#response').append(' <label>State:</label><select class="state" id="state"> </select> ');
$('#response select').append($("<option />").val('').text('Select'));
$.each(data,function(index, value){
$('#response select').append($("<option />").val(value.id).text(value.name));
});
//add above code to your ajax success - code ends here..
$.ajax({
type: "GET",
url: "process-request.php",
data: { country : selectedCountry }
}).done(function(data) {
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<label>Country:</label>
<select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
<td id="response">
</td>
</tr>
</table>
</form>
</body>
</html>
&#13;
答案 1 :(得分:-1)
我认为你应该尝试这种AJAX语法。
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { country : selectedCountry }
success: function(data){$("#response").html(data);},
error: function(err){}
})
});