Default value not displaying in new dynamic created row input field in php

I’m working on a small HTML form integrated with a table. The table has an input field named “name” which have default value from some variable $name as a default value with other two input field (city and country) without any default value. This works well for the first row. However, when I dynamically add more rows, the new input fields don’t display the default value $name in new dynamic created row field. Here’s my current code setup:

<table class="table table-bordered">
    <thead class="table-success" style="background-color: #3fbbc0;">
            <th width="15%"><center>Name</th>
            <th width="15%"><center>city</th>
            <th width="15%"><center>country</th>
            <th width="5%"></th>
                <button type="button" class="btn btn-sm btn-success" onclick="BtnAdd()">Add Item</button>                         
    <tbody id="TBody">                  
        <tr id="TRow" class="d-none">
                <input type="text"  name="name[]" id="name" value = "<?php echo $name; ?>">
                <input type="text"  name="city[]" id="city" >
                <input type="text"  name="country[]" id="country" >
            <td class="NoPrint">
                <button type="button" onclick="BtnDel(this)">x</button>

Script to add deynamic rows in table

<script type="text/javascript">

function GetPrint()
    /*For Print*/

function BtnAdd()
    /*Add Button*/
    var v = $("#TRow").clone().appendTo("#TBody") ;
        source: 'backend-script.php'  
    $(v).find("th").first().html($('#TBody tr').length - 1);

function BtnDel(v)
    /*Delete Button*/

        function(index) {

You are explicitly setting the elements value to the empty string after you add it:


Inputs have a defaultValue property you can use to determine what the default is. Use that when setting the value instead.

$(v).find("input").each((idx,ele) => ele.value=ele.defaultValue);

but my default value came from some variable. as mentioned in my code value = “<?php echo $name; ?>”
how ti handle such situation ???

Your PHP code is irrelevant after the page is loaded. The input’s default value is whatever the value=“” attribute was set to in the HTML when the page was loaded, which will be whatever your PHP code generated.

yes but the $name value came from previous html form via post method.
such as
$name = $_post[‘name’];
and later i want to enter this value into dynamic created another form

If you want a different value than whatever the first row had as it’s default, then you’ll have to make a background request to your server to obtain that value and set it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.