简体   繁体   中英

JavaScript / jQuery - taking input from 2 drop down identical menus

I have 2 drop down lists, which both hold the same list of teams , one to be used as the home team and one as the away team. At the moment the first drop down list works, when a team is selected from the list, it's id and name is output to the page. But when the other drop down is clicked, nothing happens. So for example the output takes the id and team name and outputs them to the textboxes.

Here is an example of each drop down list and the relevant code below, can anyone help me out?

HTML generated for home team list:

<select id="teamList" style="width: 160px;">
<option></option>
<option id="1362174068837" value="1362174068837" class="teamDropDown">Liverpool</option></select>

HTML generated for away team list:

<select id="teamList" style="width: 160px;">
<option></option>
<option id="1362174068837" value="1362174068837" class="teamDropDown">Liverpool</option>
</select>

JADE template used to generate the HTML (used for both lists):

div#teamDropDownDiv
    -if(teamsList.length > 0){
        select#teamList(style='width: 160px;')
            option
                -each team in teamsList
                    option.teamDropDown(id="#{team.key}",value="#{team.key}") #{team.name}

JavaScript for the page:

 Team.initTeamsDD = function(){
  $("#teamList").change(function(e){
    e.preventDefault();
    var teamId = $(this).val();

    $.get('/show/team/'+teamId, function(response){
      if(response.retStatus === 'success'){
        var teamData = response.teamData;
        $('#teamId').val(teamData.key);
        $('#teamName').val(teamData.name);
      } else if(response.retStatus === 'failure'){

      }
    });  
  });

The two <select> elements both have the same "id" value, which is "teamList". You should never have two elements with the same "id". Because of this, the on-change event handler is getting attached to only one of them. You should change them to "homeTeamList" and "awayTeamList", and then use:

Team.initTeamsDD = function(){
  $("#homeTeamList, #awayTeamList").change(function(e){
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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