Date picker JS: how to have it work on multiple form fields

南笙酒味 提交于 2019-12-10 10:52:50

问题


I am using this plugin with WP: http://wordpress.org/plugins/cf7-datepicker-alternative/

The .js file includes this code:

jQuery(document).ready(function($) {
  $('#fieldName1').datepicker({
     autoclose: true
  });
});

Does anyone know how to doctor this bit of code so the date picker will function in multiple fields in the same form, such as fieldName2 and fieldName3 as well as fieldName1?

I thank you in advance for your efforts.


回答1:


Instead of using id attribute, assign a meaningful class e.g. datepicker to the elements you want datepicker on. Then update your javascript to use that class selector.

Example:

<!-- HTML -->
<input type="text" id="fieldName1" class="datepicker" />
<input type="text" id="fieldName2" class="datepicker" />

// jQuery
jQuery(document).ready(function($) {
  $('.datepicker').datepicker({
     autoclose: true
  });
});

Update:

If you don't want to use class selectors and would want to use multiple ids, then you could do something like following:

<!-- HTML -->
<input type="text" id="fieldName1" />
<input type="text" id="fieldName2" />

// jQuery
jQuery(document).ready(function($) {
  $("#fieldName1, #fieldName2").each(function() {
     $(this).datepicker({
       autoclose: true
     });
  });
});



回答2:


Instead of using an ID to identify your Input, use a class to identify multiple Inputs

<input id="fieldName1" class="datefield" />

$('.datefield').datepicker({
   autoclose: true
});


来源:https://stackoverflow.com/questions/18326842/date-picker-js-how-to-have-it-work-on-multiple-form-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!