简体   繁体   中英

jQuery - click (with using “.on()”) on a dynamically created element doesn't work, only double-click. Why?

I have a button that after clicking on it generates a new input (or more inputs). When I click into the newly generated input(s), I want to pop up a calendar widget.

I am doing it this way:

$('#datetime_inputs').on('click', '.new_datetime_input', function() {
  $(this).datetimepicker({
    format: 'Y/m/d H:i'
  });
});

When I click into this new input, nothing happens. When I click into that 2nd time, the widget is loaded (good). If I click there 3rd time, the widget is loaded (good), 4th time - the widget is loaded (good) and so on.

Why when I click there the first time the widget is not loaded?

Thank you.

EDIT: The plugin I use link .

Change your code to:

$('.new_datetime_input').datetimepicker({
    format: 'Y/m/d H:i'
});

Currently, you are initializing it on the first click, which is why nothing seems to happen.

You do not need to set and handle a click event to display it, it will be done by the plugin after calling the method as above.


EDIT

To initialize and open the datepicker on dynamically-added elements, you could do this:

$('#datetime_inputs').on('click', '.new_datetime_input', function() {

  // Do not initialize twice on same element
  if($(this).hasClass('init')) return;
  else $(this).addClass('init');

  // Initialize
  $(this).datetimepicker({
    format: 'Y/m/d H:i'
  })
  $(this).click(); // Open datetimepicker
});

1.Problem : The widget is not bounded to element, beforehand.

  1. Consequence: When you click first time, the widget code is mapped to element.

3 Solution: you need to initialize/map/bound the element before you make click event. For say on page load.

eg.

 function bindDatePicker(i){
                $("#datepick"+i).datepicker({
              changeMonth: true,
                  changeYear: true,
                  dateFormat : 'dd/mm/yy',
                  numberOfMonths:1,
                 maxDate: "+0M +0D",yearRange:"1960:2099"
                  });       
        };

if I have this function to bind a datepicker with an element with id 'datepickX',

<input type="text" maxlength="12" onclick="bindDatePicker($index);" id="datepick4" >

I will call this function on page load, and it will bind the widget with element. So next time you will click on elemtn with some Magic !!! It will open up in first time only.

This happens because on "click" you are initializing the datetimepicker. So the next time you will click it, it will be already initialized and will show the calendar to you. Just go with Jai's suggestion and initialize it during creation. It will have it's on click event, so you don't need to set it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM