-1

I have created 5 dropdowns in mvc razor view using foreach. I need to do validation if same value gets selected in more than one dropdown in jquery.

I can easily do it using the dropdown id but what if I have more number of dropdown which is created dynamically?

Is there any generic code/way to do this?

   </div>
 @Html.DropDownList("drdId"+count, new SelectList((ViewData["MYList"] as List<MYDATA>).Select(t => new { Value = t.Id, Text = t.Name }), "Value", "Text"))
                    </div>

I tried like

function test(){ var arr = new Array($("#count1").val(),$("#count2").val(), $("#count3").val(), $("#count4").val()); for(var i=0; i

how do I make array arr dynamic for more number of dropdowns?

Neo
  • 15,491
  • 59
  • 215
  • 405
  • Client-side or server-side validation? – markpsmith May 26 '14 at 15:42
  • 1
    Client-side obv. You can create a custom validator which compares the selectlist values. [Example](http://stackoverflow.com/questions/8284207/asp-net-mvc-implement-custom-validator-use-iclientvalidatable) – markpsmith May 26 '14 at 15:48
  • @markpsmith Example is not so clear any other thread ? – Neo May 26 '14 at 15:51
  • Do a search for IClientValidatable, there are lots of tutorials available, e.g. [http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) – markpsmith May 26 '14 at 15:57
  • 1
    you can add class to each of the dropdowns and then check them by loop.. some html will help,if you could provide – Naveen Chandra Tiwari May 26 '14 at 16:41

1 Answers1

1

Try the following logic. Lets suppose each dropdown has the class "testClass":

 function checkSelect(ref) {
            var len = $(".testClass").length;
            var count=0;
            for (var i = 0; i < len; i++) {
                if ($(".testClass:eq(" + i + ") option:selected").val() !="0" && $(".testClass:eq(" + i + ") option:selected").val() == $(ref).val())
                    count++;
            }
            if (count < 2)
                return true;
            else {
                $(ref).val("0");
                return false;
            }

         }

Now call this function on change of dropdown:

 $(document).ready(function () {
    $(".testClass").on("change", function () {
       if (!checkSelect($(this)))
          alert("Can not select duplicate");
      });
 });

Hope this will solve your problem.

Naveen Chandra Tiwari
  • 5,055
  • 3
  • 20
  • 26