简体   繁体   中英

jQuery Datepicker doesn't overwrite value in dynamically created input, page refresh needed

EDIT1:
So I did managed to fix this problem. But I'm not sure how. I've been using two identical forms with different IDs for different reasons (Add and Edit forms). In those forms I had inputs with IDs. But for both forms I've been using the same ID for the inputs in them. So I change those IDs to classes (how it should be). I think this was the reason for the bug.
The second thing I've changed was removing the first form in a moment I would click on the second form (Edit form/button) because It was making a trouble, trouble I didn't addresed in here and I don't think It has anything to do with my initial problem. Just writing everything I did in any case.

I'm having a problem with jQuery Datepicker and Timepicker. I'll try to describe my situation.
I have dynamically created html for my local storage values (imagine squares with it's own data in it.)

My problem... If I simply load these squares and I want to change something, by clicking on edit button, It will create a form with pre-written values in them, by clicking on one of these inputs, a calendar shows up. And then after clicking on some date, the pre-written value changes with value of a date I've clicked on. Same for Timepicker. But! There is a problem.

If I want to create new squares with new data ( by dynamically creating form with inputs, then the data is saved to local storage) and then (without refreshing the page) clicking on edit button, bringing same old form (as described above) and clicking on some of the inputs, calendar shows up, but after clicking on some date, the value of the input doesn't change. Same with Timepicker, doesn't overwrite the pre-witten value.

But if I refresh the page and want to edit something (without creating new squares/data), Datepicker change the value without problem.

Can you help me please? I'll try to answer any question if needed.

Here is a function that show everything saved in local storage.

function fetchBookmarks() {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
bookmarks.sort(function compare(a, b) {
    var dateA = new Date(a.date);
    var dateB = new Date(b.date);
    return dateB - dateA;
  });

var results = document.getElementById("results");
results.innerHTML = "";
for (var i = 0; i < bookmarks.length; i++) {
    var date = bookmarks[i].date;
    var distance = bookmarks[i].distance;
    var time = bookmarks[i].time;

    results.innerHTML += '<div class="bookmarks shadow p-3 m-2 bg-light rounded">' +
        '<div class="row">' +
        '<div class="col">' +
        '<h3>Date: </h3>' +
        '<h3>Distance: </h3>' +
        '<h3>Time: </h3>' +
        '</h3><input onclick="editBookmarks(\'' + time + '\')" class="btn btn-outline-primary mr-1 btn-lg" id="edit" type="button" value="Edit"><input onclick="deleteBookmarks(\'' + time + '\')" class="btn btn-outline-danger btn-lg" id="deleteBookmarks" type="button" value="Delete">' +
        '</div>' +
        '<div class="col">' +
        '<h3 class="font-weight-bold">' + date + '</h3>' +
        '<h3 class="font-weight-bold">' + distance + '</h3>' +
        '<h3 class="font-weight-bold">' + time + '</h3>'
    '</div>' +
        '</div>' +
        '</div>';
};

};

And here is function after clicking on edit button...

function editBookmarks(time) {
var bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
for (var i = 0; i < bookmarks.length; i++) {
    if (bookmarks[i].time == time) {
        $(".bookmarks").hide();
        results.innerHTML += '<form class="bookmarks shadow p-3 m-2 bg-light rounded" id="editForm">' +
            '<h4>Date: </h4><input class="form-control form-control-lg" id="date" placeholder="Select" value="' + bookmarks[i].date + '" type=""><br>' +
            '<h4>Distance: </h4><input class="form-control form-control-lg" id="distance" placeholder="In miles" value="' + bookmarks[i].distance + '" type="text"><br>' +
            '<h4>Time: </h4><input class="form-control form-control-lg" id="time" placeholder="Select" value="' + bookmarks[i].time + '" type=""><br>' +
            '<input class="btn btn-success btn-lg" type="submit" value="Submit">' +
            '</form>';

        /* $('#date').datepicker()
        $('#time').timepicker({
            timeFormat: "H:mm",
            hourMin: 0,
            hourMax: 4
        }); */
        bookmarks.splice(i, 1);
    };
};


$("#editForm").on("submit", function (e) {
    var date = $("#date").val();
    var distance = $("#distance").val();
    var time = $("#time").val();

    if (!distance.length || !date.length || !time.length) {
        alert("Something missing!")
    } else {
        var bookmark = {
            date: date,
            distance: distance,
            time: time
        };

        bookmarks.push(bookmark);
        localStorage.setItem("bookmarks", JSON.stringify(bookmarks));

        fetchBookmarks();
        $("#editForm").hide();
    };
    e.preventDefault();
});
$("#search").hide();
};

And here is Datepicker with Timepicker

$('body').on('focus', "#date", function () {
$(this).datepicker();
});

$('body').on('focus', "#time", function () {
$(this).timepicker({
    timeFormat: "H:mm",
    hourMin: 0,
    hourMax: 4
});
});

I know that this is quite much to ask and I'm having a problem with articulating. I'm just lost in this.
I'm thankful for any help.

Here's a link for GitHub file, I think It's better than posting the code here. My whole problem is at the bottom of the file, if you're interested.
https://github.com/ovy1448/MyRun/blob/master/js/main.js
Thanks again.

As per my understanding, since you are using onfocus event to attach datepicker/timepicker, all the event of datepicker/timepicker is not getting attached to the field. I faced similar problem 2-3 years back. What I did is that I added a function for the datepicker onSelect event which updates the field value. You can try this(as below) and let me know if it works

 $('body').on('focus', "#date", function () { $(this).datepicker({onSelect: function(dateStr){ $('body').('#date').val(dateStr); }}); }); $('body').on('focus', "#time", function () { $(this).timepicker({ timeFormat: "H:mm", hourMin: 0, hourMax: 4, onSelect: function(timeStr){ $('body').('#time').val(timeStr); } }); }); 

So I did managed to fix this problem. But I'm not sure how. I've been using two identical forms with different IDs for different reasons (Add and Edit forms). In those forms I had inputs with IDs. But for both forms I've been using the same ID for the inputs in them. So I change those IDs to classes (how it should be). I think this was the reason for the bug.
The second thing I've changed was removing the first form in a moment I would click on the second form (Edit form/button) because It was making a trouble, trouble I didn't addresed in here and I don't think It has anything to do with my initial problem. Just writing everything I did in any case.

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