None
None

Reputation: 5670

Jquery year picker not working as expected

I have created a simple jquery year-picker, with the jelp of this post And added some custom code to make yearpicker show some specific value as selected. This is my code

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<select name="yearpicker" data-id="2010" class="yearpicker">
</select>

<select name="yearpicker"  data-id="2006" class="yearpicker">
</select>

JavaScript

$(function () {
   for (i = new Date().getFullYear() ; i > 1900; i--) {

      $this = $('.yearpicker');
      if ($this.attr("data-id") != i) {
         $this.append($('<option />').val(i).html(i));
       } else {
          $this.append($('<option selected/>').val(i).html(i));
       }
    }
});

What i want is, I will bind a property named "data-id" to selection control in back end and when script runs I want that element to be selected in front end. and I have multiple selection controls in page, for some reason always first selections data-id is selected on all selections. Detailed JSfiddle is here. you can see that 2010 is selected in both cases where i expect 2006 to be selected on second <select/> Can any one point out what I am doing wrong?

Upvotes: 2

Views: 263

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82231

Try this:

$(function () {
   $('.yearpicker').each(function(){
      for (i = new Date().getFullYear() ; i > 1900; i--) {
         $this = $(this);
         if ($this.attr("data-id") != i) {
            $this.append($('<option />').val(i).html(i));
         } else {
            $this.append($('<option/>').val(i).attr("selected", "selected").html(i));
         }
      }
   });
});

Working Fiddle

Upvotes: 5

Ramesh
Ramesh

Reputation: 4293

Change this line:

$this.append($('<option selected/>').val(i).html(i));

to

$this.append($('<option/>').val(i).html(i).attr("selected", "selected"));

Complete code:

  $(function () {
  $('.yearpicker').each(function() {
      $this = $(this);
              for (i = new Date().getFullYear() ; i > 1900; i--) {


            if ($this.attr("data-id") != i) {
                $this.append($('<option />').val(i).html(i));
            } else {
                $this.append($('<option/>').val(i).html(i).attr("selected", "selected"));
            }
        }
  });

});

Upvotes: 1

Related Questions