javascript - 如何在第一个组合框更改后获取第二个组合框值(jquery)

标签 javascript jquery select combobox onchange

我有 2 个组合框,第一个用于省份,第二个用于城市/城镇。

我只想在第一个组合框更改后获取第二个组合框(城市/城镇)的值,并且在用户选择第一个组合框后第二个组合框将通过ajax更改。

这是我的代码,但问题是警报出现了两次!

jQuery('#billing_state').on('change', function() {
    jQuery('#billing_city').on('change', function() {
          var state = jQuery(this).val();
          alert(state);
    });

});

最佳答案

为什么你要对事件进行叠瓦式排列?只需对第一个组合使用更改即可。

这是一个例子:

state = {"1":["Rome","Milan","Parma"],"2":["Paris","Lile","Nice"],"3":["Algiers","Jijel","Bejaia"],"4":["London","Manchester"]}


$(document).ready(function(){
	//this if you want that changing province this alert country value
    $("#billing_state").on("change",function(e){
  	    
          $("#billing_town").children().remove();
          var city =state[$(this).val()];
          if(!city) return;
          $("#billing_town").append('<option value="">- Select -</option>')
          for(i=0; i< city.length;i++) {
            //console.log(city[i]);
            $("#billing_town").append('<option value="'+city[i]+'">'+city[i]+'</option>');
          }
          
    });
  
    // when changing country this alert country value itself
    $("#billing_town").on("change",function(e){
  	    alert($(this).val());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Province :
<select id="billing_state">
  <option value="">- select -</option>
  <option value="1">Italy</option>
  <option value="2">France</option>
  <option value="3">Algeria</option>
  <option value="4">UK</option>
</select>
<br><br>
Country : 
<select id="billing_town">
</select>

关于javascript - 如何在第一个组合框更改后获取第二个组合框值(jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39138794/

相关文章:

javascript - 无法为 html5 Canvas 上的矩形设置背景颜色

javascript - 检测是否处于全屏模式(3d 动画书)

jQuery 垂直巨型菜单子(monad)菜单在加载时闪烁。如何阻止wordpress中的闪烁

MYSQL JOIN 两个表按日期限制第二个表的结果

r - 如何根据两个变量对数据进行子集化

javascript - axios如何将Windows身份验证 header 发送到API

javascript - Angular Ionic UI-Router - 如何确保在嵌套状态下启动应用程序时加载所有父 View ?

jquery - 单击时打开/关闭 CSS 过渡

javascript - tablesorter 从选择下拉菜单和自定义时间过滤器中选择多个选项?

MySQL if/条件查询?