0

I'm dynamically generating multiple dropdown lists on button click, with the same currency values. Now I've to compare that none of the dropdown lists should have the duplicate value. Eg. On button click I generated a

Dropdownlist1, Dropwdownlist2, Dropwdownlist3

and

Dropdownlist4

and all have same values, let's say

1,2,3,4,5

Now if I've selected 2 in any of the lists then this value should not be allowed to select from any of the remaining lists.

Since, I'm generating the lists dynamically so I'm not having multiple Ids also. I tried from my end but I could compare the selected value for only two lists and with static ids. Thank you.

 $("#currenciesList2").change(function() {
        if ($(this).val() === $("#currenciesList1").val()) {
            alert('Duplicate currency value');
            $(this).val('');
        }
    });
10
  • You have to give them separate id's if I'm correct. What you could do is just generate id's using a count of the number of dropdowns created. Ps. It'd be great if you could add a fiddle so I can show you what I mean Commented Feb 19, 2016 at 20:26
  • Get Selected Values of the selected dropdown list using $(this).val() and then remove that value from the other dropdownlists using $("option[value='"+$(this).val()+"']").remove(); let me if it looks ok to you then i will be giving complete code Commented Feb 19, 2016 at 20:32
  • @HeemanshuBhalla Yes, this approach also looks fine, please provide the code. Thanks. Commented Feb 19, 2016 at 20:36
  • @Evochrome I'll add a fiddle. Thanks. Commented Feb 19, 2016 at 20:36
  • @user1547554 Please check a sample code i provide accept the answer if it helps Commented Feb 19, 2016 at 20:37

5 Answers 5

1

Another option is generating the Id's for the dropdownmenu's like this:

Note that Choose... doesn't dissappear as it doesn't have a value assigned

$(document).ready(function(){
  var count = 1; //number of select
  var c; //string var of count, not neccessary but better
  var used = new Array;

	$("#gen").on("click", function(){
		c = count.toString(); //Not neccessary but better
		$("#container").append("<select id='select"+c+"' class='selector'><option>Choose...</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option></select>");
		count++; //count + 1
  });
  

  $("#container").change(function(){
  	$("option").each(function(){//For each option
    	$(this).show(); //show all options
    });
			for (i=1; i<count; i++){
    		used[i-1] = $("#select"+i).val();//used options
        for (j=1; j<used.length; j++){
          for (p=0; p<used.length; p++){
          	if(j!==p){
            	if($("#select"+i).children('option[value="'+used[p]+'"]').length !== 0){//check children of selects for duplicate values
              	$("#select"+i).children('option[value="'+used[p]+'"]').hide()//hide duplicates
              }
          	}
          }
        }
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>    
 
 <button id="gen">
   generate select
 </button>

Hope it helped! :)

EDIT: Value filtering added! :)

Sign up to request clarification or add additional context in comments.

Comments

1

What we are doing is We are getting the selected value of current dropdownlist then we are checking if its index is 1 then remove that index in other dropdownlists also assuming all other dropdown list have same index for values

$(function () {

    $("#drop_down_list1").change(function (){
        var select = $("#drop_down_list1").val();  
    if (select!='') {
            $("#drop_down_list2").find("option[value='" + selected + "']").remove();
            $("#drop_down_list3").find("option[value='" + selected + "']").remove();


        }


    })
});

In Case of Having more Dropdownlist like 100 or more we can assign class to dropdown lists and Then we can Use Foreach Loop Through all Dropdowns and do the same find function to remove the values selected as shown below

 //In Case of Have More DropDowns
  var select = $("#drop_down_list1").val(); 
     $(".AllDropDowns").each(function() {

               $(this).find("option[value='" + select + "']").remove();

        });

7 Comments

Yes, all the dropdown lists have same index for values. Could you please tell me, how can I make it more generic with dynamically generated Ids, since user can generate upto 100 such lists. Thanks.
@user1547554 if you have more number of dropdowns then use class instead of id . I have updated the code
@user1547554 I updated the code if we have multiple dropdowns by using foreach try that one hope it works
Thank you. Let me try this out. Thank you. :)
Using this approach, you could eventually end up with completely empty lists: selecting a value removes that value from the other lists, but then what if you change that selection again? Are you re-adding that value to the other lists?
|
1

You can assign them all a known class name, then in JQuery select all SELECT elements with that class, and get the selected option value of each.

You should probably avoid removing the options, unless you're going to also add a mechanism to re-add the values once the original selection is changed. A better approach might be to allow the duplicated selection, but test for it and avoid submitting the form if duplicates are selected. This should get you started along that path:

function test() {
  var usedVals = [];
  $('#errorMsg').hide();
  
  $('.avoidDupeSel').each(function() {
    if (-1 !== $.inArray($(this).val(), usedVals)) {
      $('#errorMsg').html('Duplicated values selected');
      $('#errorMsg').show();
  	}
  	usedVals[i++]	= $(this).val();
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="randomId123" class="avoidDupeSel">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
<select id="randomId456" class="avoidDupeSel">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
<select id="randomId789" class="avoidDupeSel">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

<input type="button" onclick="test()" value="Submit" />
<span id="errorMsg"></span>

1 Comment

I tried to run this code but it doesn't display any message or alert in case of duplicate values.
1

I did somthing similar a while ago but its all in JS im afraid, you will need div with class to attach it to

var ListItem = [1,2,3,4,5];
var ListItemSelected = [];

var Dropdown = (function ()
{
     var Class = function (div)
     {
        this.div = $(div);
        this.dropdown = $("<select></select>");
        this.div.append(this.dropdown);
        this.val = null;
        this.target = null;
        this.PopulatedDropdown = populatedDropDown();
        populatedDropDown.call(this);
        addEvent.call(this);
     }

     function addEvent()
     {
         var me = this;
         me.dropdown.change(function ()
         {
             me.val = me.dropdown.val(); 
            ListItemSelected[ListItemSelected.length] = me.dropdown.val(); 
            if(this.target != null)
            {
                for(var i = 0; i < this.target.length; i++
                {
                   if(this.target[i] != this)this.target[i].PopulatedDropdown(); 
                }
            }
         }
     }

     function populatedDropdown()
     {
        for(var i = 0; i < ListItem.length; i++ )
        {
           var isUsed = false;
           var firstItem = null;
           for(var j = 0; j < ListItemSelected.length; j++)
           {
               if(ListItem[i] == ListItemSelected[j] && ListItem[i] != this.val)
               {
                   isUsed = true;
                   break;
               }
           }
           if(!isUsed)
           {
              var option = $("<option></option");
              option.value = ListItem[i];
              option.text(ListItem[i]);
              this.dropdown.append(option);
              if(firstItem == null) firstItem = ListItem[i];
           }
        }

        if(this.val !=null ) this.dropdown.val(this.val);
        else this.dropdown.val(firstItem );
      }
   (Class.prototype);
    return Class;
}

after you need to create dropdown object and attach ref to target

var div = document.getElementsByClassName(".dropdownClass");
var dropdown = [];
for(var i = 0; i < div.length; i++)
{
   dropdown[i] = new Dropdown(div[i]); 
}

for(var i = 0; i < dropdown.length; i++)
{
   dropdown[i].target = dropdown; 
}

Comments

1

Using a class instead of ids you can do it dynamically no matter how many drop-downs you have and their ids:

        <select class="drop_down_list">
              <option class=" requiresCVV2" value="">Choose...</option>
              <option id="CCType_DISCOVER" class=" requiresCVV2" value="DISCOVER">Discover</option>
              <option id="CCType_MC" class=" requiresCVV2" value="MC">Mastercard</option>
              <option id="CCType_VISA" class=" requiresCVV2" value="VISA">Visa</option>
        </select>
        <select class="drop_down_list">
              <option value="">Choose...</option>
              <option id="CCType_DISCOVER"  value="DISCOVER">Discover</option>
              <option id="CCType_MC" class=" requiresCVV2" value="MC">Mastercard</option>
              <option id="CCType_VISA" value="VISA">Visa</option>
        </select>
        <select class="drop_down_list">
               <option value="">Choose...</option>
               <option id="CCType_DISCOVER"  value="DISCOVER">Discover</option>
               <option id="CCType_MC" value="MC">Mastercard</option>
               <option id="CCType_VISA"  value="VISA">Visa</option>
        </select>

This will solve your problem but you will need some reset mechanism to restore the values and start the selection again in case was wrong.

function dropDowns() {    
  $(".drop_down_list").change(function(){
      //Hide the option selected in all the others dropdowns  
      $(this).siblings("").children().filter("option[value='" +$('option:selected',this).val()+"']").hide();     
    });  
} 

You can test it here and see if it's what you want: https://jsfiddle.net/z3tc2jbq/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.