Skip to content
Advertisement

Change Text box value based on Data list selected value – PHP

I’ve created a table with two columns ‘id’ and ‘names’ and in my PHP(html) page added data list and text area to display it, data list options are filled with ‘id’ and i want the text area to show the ‘name’ of the ‘id’ i selected in the data list.

  userid | name   |
   ----------------
    1    | name 1 |
    2    | name 2 | 
    3    | name 3 |
    4    | name 4 |

This is my part of the code –

<input list="uid" class="custom-select" id="dlist" name="dlist">
        <datalist id="uid">
        <?php
        $sql = "SELECT * FROM userdata";
        $result = mysqli_query($link, $sql);
        if (mysqli_num_rows($result) > 0) 
        {
        // output data of each row
          while($row = mysqli_fetch_assoc($result)) 
          { 
          echo'<option value="'. $row["userid"].'">';
          }
        } 
        ?>
         </datalist>
        <textarea class="form-control" id="uname" rows="4" name="uname"></textarea>

I looked up to some of the answers, some of them said to use ajax, but i’ve not gotten a good example to refer and complete my code. If this was already solved, please comment answer links.

Advertisement

Answer

Well, i’ve made it work in a very different way, i.e data-value and with the help of this answer – https://stackoverflow.com/a/48076273/14890948

<input list="uid" class="custom-select" id="dlist" name="dlist">
        <datalist id="uid">
        <?php
        $sql = "SELECT * FROM userdata";
        $result = mysqli_query($link, $sql);
        if (mysqli_num_rows($result) > 0) 
        {
        // output data of each row
          while($row = mysqli_fetch_assoc($result)) 
          { 
          echo'<option data-value="'. $row["name"].'"value="'. $row["userid"].'">';
          }
        } 
        ?>
         </datalist>
        <textarea class="form-control" id="uname" rows="4" name="uname"></textarea>


$("#dlist").on("change", function () {
    
   var value = $('#dlist').val();
      value = $('#uid [value="' + value + '"]').data('value');
      $('#uname').val(value);
      
    });
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement