开发者

Why are all my fields updated when I change one?

I use the JQu开发者_如何学编程ery datepicker, and the problem is that I generate the HTML, so I don't know in advance the ID's of the fields.

My code can be tried at http://jsfiddle.net/littlesandra88/KrEqk/

The forms below are generated, where the ID's just get prefixed with a random number to make them different.

What I did to get datepicker in those fields was to add class="datepick" to those fields like so

<input name="from" id="114_begin_date" value="16/05-2011" type="text" class="datepick" />
<input name="to"   id="114_end_date"   value="16/05-2011" type="text" class="datepick" />

and add .datepick to the inline datepicker JavaScript, like so

var dates = $("#from, #to, .datepick").datepicker({         

If you try to change the dates several times you will notice, that all fields are updated =(

How do I prevent that from happening, so just the field that I click on is changed?


The problem is in the onSelect handler

You are running

dates.not(this).datepicker("option", option, date);

this changes all the other datepickers to a single value (the one of the current datepicker)..


Update for comment

change your onSelect method to

onSelect: function(selectedDate) {
                  var self = this;
                  var option = this.name == "from" ? "minDate" : "maxDate",
                  instance   = $(this).data("datepicker"),
                  date       = $.datepicker.parseDate(
                                  instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
                  dates.filter(function(){return this.form === self.form;}).not(this).datepicker("option", option, date);
               } 

changes made

  1. added the var self = this; for later use
  2. use the name attribute instead of the id to decide which limit to use
  3. instead of applying the new date limit to all other datepickers (i assume you took that part from somewhere where only two datepickers existed), we filter them down to the ones that are in the same form as the one we changed. (in effect the other one, in the same line. Keep in mind that this works only for two datepickers per form named from and to)

demo at http://jsfiddle.net/gaby/Wy6qT/


Hm, i'm not familiar with datepicker, but you could try:

$("#from, #to, .datepick").each(
    $(this).datepicker({/*... some settings? */});
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜