Implementing Bootstrap Datepicker within the dynamically generated table rows

I am currently in the process of developing a data grid for a project and I am encountering an issue with implementing Bootstrap Datepicker on the Date field within the table. The problem arises when trying to use the datepicker on subsequent rows that are dynamically created after the initial row - it seems to only work on the first row.

Could someone provide assistance or guidance on how to ensure that the datepicker functions correctly on every newly created row, specifically on the Date field?

Below you will find the code snippet:

function getElementsByClassName(c,el){
    if(typeof el=='string'){
        el=document.getElementById(el);
    }
    if(!el){
        el=document;
    }
    if(el.getElementsByClassName){
        return el.getElementsByClassName(c);
    }
    var arr=[],
        allEls=el.getElementsByTagName('*');
    for(var i=0;i<allEls.length;i++){
        if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
    }
    return arr;
}

function killMe(el){
    return el.parentNode.removeChild(el);
}

function getParentByTagName(el,tag){
    tag=tag.toLowerCase();
    while(el.nodeName.toLowerCase()!=tag){
        el=el.parentNode;
    }
    return el;
}

// Delete table row
function delRow(){
        killMe(getParentByTagName(this,'tr'));
}

// Insert table row
function addRow() {
    var table = getParentByTagName(this,'table')
    var lastInputs=table.rows.length>2?
        table.rows[table.rows.length-2].getElementsByTagName('input'):[];
    for(var i=0;i<lastInputs.length-1;i++){
        if(lastInputs[i].value==''){return false;}
    }

    // New table row vars
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount-1);
    

    var cell1 = row.insertCell(0);
    var element1 = document.createElement("input");
    element1.id = "expenseDate";
    element1.type = "text";
    element1.className="form-control datepicker";
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    element2.className="form-control";
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement("input");
    element3.type = "text";
    element3.className="form-control";
    cell3.appendChild(element3);

    var cell4 = row.insertCell(3);
    var element4 = document.createElement("input");
    element4.type = "text";
    element4.className="form-control";
    cell4.appendChild(element4);
    

    var cell5 = row.insertCell(4);
    var element5 = document.createElement("input");
    element5.type = "button";
    element5.className="del btn btn-sm btn-danger";
    element5.value='X';
    element5.onclick=delRow;
    cell5.appendChild(element5);

}
#ExpensesTable {
margin-top: 30px;
}

#ExpensesTable tr {
margin: 10px 0px 10px 0px;
}

#ExpensesTable td {
padding: 5px 5px 0px 5px;
}
#ExpensesTable th {
padding: 0px 5px 5px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head> 
<body>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="bootstrap-datepicker.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="container">

<table id="ExpensesTable">
    <tr>
        <th>Date:</th>
        <th>From:</th>
        <th>To:</th>
        <th>Nr. Km:</th>
    </tr>
    <tr>
    <td><input class="add btn btn-sm btn-success" type="button" value="Add expense" id="AddExpense"/></td>
    </tr>
</table>

</div>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="bootstrap-datepicker.min.js"></script>

<script type="text/javascript">
    (function(){
    var els=getElementsByClassName("add","ExpensesTable");
    for(var i=0;i<els.length;i++){
        els[i].onclick=addRow;
    }
    els[0].onclick();
    })();
</script>
<script>
$('#expenseDate').datepicker({
});
</script>

</body>
</html>

Answer №1

Optimize your coding process with jQuery and watch as 4-5 lines of code accomplish what you need :)

Cheers,

$('.dateP').datetimepicker();

$('.dupli').on( 'click', function(e){
  var dup = $('.cpy').first().clone();
  $('.table').append( dup );
  $('.dateP').datetimepicker();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/css/bootstrap-datetimepicker.css" rel="stylesheet"/>



<table class="table table-striped">
    <tr>
        <th>Event name</th>
        <th>Date:</th>
        <td><button type="submit" class="btn btn-default dupli">+</button></td>
    </tr>
    <tr class="cpy">
        <td>
            <input type="text" class="form-control" id="e1">
        </td>
        <td>
          <div class='input-group dateP'>
              <input type='text' class="form-control" />
              <span class="input-group-addon">
                  <span class="glyphicon glyphicon-calendar"></span>
              </span>
          </div>
        </td>
    </tr>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sort through an array of objects by their respective values within another array of nested objects

I am struggling to filter out positions from the positions array that are already present in the people array. Despite trying different combinations of _.forEach and _.filter, I can't seem to solve it. console.log(position) var test = _.filter(posi ...

Deactivate toggle effect by clicking on a different link

My existing JavaScript code changes the background color of a link when it is clicked: $(".button").click(function(){ $(this).css('background-color', '#555'); }); While this functionality works, I am looking to have the color tog ...

Retrieve the key value from the specified input ID using jQuery

I have a list containing multiple input fields <input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" /> <input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" /> <?php if ($ ...

utilizing YouTube API for real-time updates

Is there a YouTube API equivalent to the HTML5 video's ontimeupdate event that is not documented or known? I have attempted using a setInterval method but it requires additional checks for video play status. Has anyone encountered this problem before? ...

I'm having trouble locating the module "script!foundation-sites/dist/foundation.min.js on Heroic."

This is the content of my webpack.config.js file: var webpack = require('webpack'); var path = require('path'); process.env.NODE_ENV = process.env.NODE_ENV || 'development'; module.exports = { entry: [ 'script!jque ...

Displaying a message when there are no results in Vue.js using transition-group and encountering the error message "children must be keyed

Utilizing vue.js, I crafted a small data filter tool that boasts sleek transitions for added flair. However, I encountered an issue with displaying a message when there are no results matching the current filters. Here's what I attempted: <transit ...

Creating Images that appear optimized on smaller screens - the art of responsive design!

Currently, I am in the process of working on this test page located at the following link: While the page appears fine on my laptop screen, it is displaying poorly on my phone's browser. The images, in particular, appear disorganized and messy. Coul ...

mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error: Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl My main goal is to display ...

Tips for detecting a change in a Django Autocomplete Light widget with jQuery

Currently, I am incorporating Django Autocomplete Light (DAL) within my application. To perform additional processing in the background upon user selection, I am attempting to detect the .on('change') event (specifically when the DAL select fiel ...

Ensure that the second ajax call retrieves the first result every time

This is the code snippet I am currently using: <script type="text/javascript> $(function() { $('#DoTask').click(function(event) { event.preventDefault(); // added this $.getJSON('/TareasBackGround/DoTaskInteractivo ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...

Styling Scrollbars in Datatables

I need assistance on styling a specific datatable scrollbar using Webkit. Below is the code snippet: id ::-webkit-scrollbar-track { background-color: transparent; border-radius: 5px; } id::-webkit-scrollbar { width: 13px; } ...

Angular JS appears to be failing to properly establish values in the Dropdownlist

I have a project requirement to connect a dropdownlist with MVC and angular JS. Here is my attempt: var app1 = angular.module('Assign', []) app1.controller('SAPExecutive_R4GState', function ($scope, $http, $window) { // alert(UMS ...

Transmit ASP Webform data through Visual Studio to an external API

While working on a webform project in Visual Studio, I encountered an issue when trying to send data from the form fields to a 3rd party API using a POST request. Despite my attempts to use JSON to capture the form field data and send it as a JSON object, ...

Deleting the HTML element

Can someone assist me with my script issue? I am facing a problem: when I open my file on fullscreen (over 768px), and move my pointer around the logo div, nothing happens. However, if I resize my browser to below 768px, then back again above 768px, the ...

Change JSON to an unordered list using <ul> and <li

I came across an item that resembles the following: { "qA": [ { "question": "How deep is the ocean", "answer": [ "quite deep", "very deep", "no deep at all" ] ...

The most effective way to transmit data from an asynchronous call in Node.js while ensuring a reliable fallback routing structure

I have a request function that makes a call to an endpoint and retrieves data from it. When passing this data to an hbs template for rendering, the array is empty due to asynchronicity. Can someone guide me on the correct approach? Below is the code snippe ...

The request payload appears as [Object Object] when initiating the AJAX post request

Currently, I am making an AJAX request with the specified data. The data being sent is an object and my intention is to send the object itself without converting it to a JSON string. However, when viewing the request in the browser, the payload is shown as ...

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Having trouble setting margin-bottom to 0 in react and antd - why won't it reset?

While practicing with React, I added <link rel="stylesheet" href="%PUBLIC_URL%/css/reset.css" /> to the head of index.html in order to reset the styles. However, I noticed that <h1> still had a margin-bottom:0.5em that I c ...