简体   繁体   English

从下拉菜单发送最后选择的值

[英]Sending last selected value from drop down menu

I have a problem when selecting an option from a drop down menu. 从下拉菜单中选择选项时出现问题。 The concept goes like this: 这个概念是这样的:

  1. Select a country (lets say UK) 选择一个国家(让我们说英国)
  2. Select a city by clicking on it(ex. London), then select Manchester, then London again and finally select Leeds ( London -> Manchester -> London -> Leeds). 通过单击城市(例如伦敦)选择一个城市,然后选择曼彻斯特,再选择伦敦,最后选择利兹(伦敦->曼彻斯特->伦敦->利兹)。

**Both city drop down menu and "Add" button are future DOM elements, so i use delegation. **城市下拉菜单和“添加”按钮都是将来的DOM元素,因此我使用委托。

While doing this i will get the following results in FIRST console.log : 这样做时,我将在FIRST console.log获得以下结果:

1 1

2 2

1 1

3 3

  1. As soon as i press the "Add" button i see the following results in SECOND console.log : 我按下“添加”按钮后,立即在SECOND console.log看到以下结果:

1 1

2 2

1 1

3 3

My problem is that it sends all the values previously selected until i press the "Add" button instead of sending just the last selected value (value 3). 我的问题是它会发送以前选择的所有值,直到我按下“添加”按钮,而不是仅发送最后一个选择的值(值3)。

What do i do wrong? 我做错了什么?

Thanks! 谢谢!

code below: 下面的代码:

<select id="city" name="city">
     <option value="1">London</option>
     <option value="2">Manchester</option>
     <option value="3">Leeds</option>
</select>

<button type="button" id="addToDatabase">Add</button>

$(document).on('change','select#city',function(){

   var cityID = $('select#city').val();

   console.log(cityID); //first console.log

   $(document).on('click','#addToDatabase',function(){

       console.log(cityID);//second console.log

       $.post('js/ajax/addtodatabase.php', {cityID: cityID},

           function(output){

               console.log(output);//third console.log

            }
        );

   }); 
});

Try without nesting your functions as follows, an in the second function use $('#city').val() instead of cityId var since now they are not nested: 尝试不嵌套您的函数,如下所示,在第二个函数中使用$('#city').val()而不是cityId var,因为现在不嵌套它们:

 $(document).on('change','select#city',function(){ var cityID = $(this).val(); console.log(cityID); //first console.log }); $(document).on('click','#addToDatabase',function(){ console.log($('#city').val());//second console.log $.post('js/ajax/addtodatabase.php', {cityID: $('#city').val()}, function(output){ console.log(output);//third console.log } ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="city" name="city"> <option value="1">London</option> <option value="2">Manchester</option> <option value="3">Leeds</option> </select> <button type="button" id="addToDatabase">Add</button> 

Hope this helps, 希望这可以帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM