Leron
Leron

Reputation: 9866

Adding jQuery datepicker for more than one text box in asp.net mvc 3

I am working on an asp.net mvc 3 application. In one of my partial views I render all fields that should provide the option to select date. I use the jQuery datepicker plugin and some sample code I found on the net :

if (field[i].MCS_Fields.FieldTypeId == 2)
                    { 
                        <script type="text/javascript">
                            $(function () {
                                $(".datepicker").datepicker();
                            });
                        </script>
                        @field[i].QuestionText;
                        @Html.TextBox("datepicker", "", new { @class = "datepicker" })
                    }

The problem is that if I do this for more than one @Html.TextBox no matter where I pick the date the change will be made only on the first textbox with class="datepicker". I have almost no experience with JS, jQuery and so on, so could you suggest a way that will allow me to add N number of @Html.TextBox and being able to pick a date for each one separately?

Upvotes: 1

Views: 897

Answers (2)

Keren Caelen
Keren Caelen

Reputation: 1466

You can use: Using each function:

  $(".datepicker").each(function() {
        $(this).click(function() {
            $(this).datepicker();
        });
    });

If this is not working, then you can use this also:

<script type="text/jscript">
     $(function () {
         $("#StartDate").datepicker();
     });
  </script>

Here StartDate will be id of your datepicker. and you can write this in your view

Upvotes: 1

Jarvan
Jarvan

Reputation: 1220

Put this on your page bottom,it will render all datepickers:

$(".datepicker").each(function() {
    $(this).datepicker();
});

Edit: If it doesn't work i guess may be you put it in wrong place so the code run before html rendered,try this

$(document).ready(function(){
    $(".datepicker").each(function() {
        $(this).datepicker();
    });
});

see jsfiddle

Upvotes: 1

Related Questions