Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - jQuery UI Datepicker Date Range

I am using the jQuery UI plugin with the Datepicker function, to set a date range. The example provided on their page (http://jqueryui.com/demos/datepicker/date-range.html) sets the range based on input 'id'; however, I'd like to set the range based on 'class' as my form 'clones' the div to add additional inputs, making the 'id' fields unique on each clone. When I change the JavaScript to use 'class' instead of 'id', the ranges are no longer functioning.

JavaScript:

<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.datepicker.js"></script>
<script>
        $(function() {
            var dates = $( ".start_date, .end_date" ).datepicker({
                onSelect: function( selectedDate ) {
                    var option = this.class == "start_date" ? "minDate" : "maxDate",
                        instance = $( this ).data( "datepicker" ),
                        date = $.datepicker.parseDate(
                            instance.settings.dateFormat ||
                            $.datepicker._defaults.dateFormat,
                            selectedDate, instance.settings );
                    dates.not( this ).datepicker( "option", option, date );
                }       
            }); 
        });
</script>

HTML:

<div>
    <label> Start Date:</label>
    <input type="text" name="start_date1" id="start_date1" class="start_date" />
</div>
<div>
    <label> End Date:</label>
    <input type="text" name="end_date1" id="end_date1" class="end_date" />
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To check to see if your element has a class, do this:

 if ($(this).is('.start_date')) {

or

 if ($(this).hasClass('start_date')) {

The name of the property of DOM elements is "className", not "class" (confusingly). Also it makes your code fragile to check for the class name to be equal to some string, because you never know if you might want to add another class (like "required" for example). Thus you should always check either with jQuery or with some other method that accounts for the possibility that an object can have many classes.

Also you may want to check out the Filament Group's date range picker for jQuery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...