skip to Main Content

I create a website, which can extract data from api, and do CRUD

now my "delete", "edit" button works fine and done

  • edit button pic

(pic)

Q: the add button, how can I make default value is empty ,I apply similar method as "edit" button, will pop up a form to fill up the new data and send (the only difference is from "edit", has the old data, and "add" button is null for the column)

cause I done "edit" button , I though "add" button shall be easier

  • I simpler the code, but the concept is same
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Meta tags and other head elements -->
  <title>Static Template</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.css"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap 4.2.1 CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
  
   
</head>
<body>

  

  <div id="app"></div>
  <table id="example" class="display"></table>

  <!-- JavaScript libraries -->
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>



  <script>
    $(document).ready(function () {
      const getToken = localStorage.getItem("token")

      console.log("GET TOKEN", getToken)

      var table = $("#example").DataTable({
        ajax: {
          url: "http://192.168.0.0:3000/api/product01",
          headers: {
            'Authorization': 'Bearer ' + getToken
          },
          dataSrc: function (response) {
            console.log("DATA", response.ipcs);
            return response.ipcs
          }
        },
        columns: [
          {
            data: null,
            title: "ACTION",
            render: function (data, type, row) {
              return '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever=" ">Edit</button>' +
                '<button class="btn btn-danger btn-sm delete-btn" data-id="' + row.device_id + '">Delete</button>';
            }
          },
        
          
          { data: "device_id", title: "device_id" },
          { data: "name", title: "name" },
          { data: "group", title: "group" },

        ]
      });


      table.draw()
      

      var rowData; 

      $('#example tbody').on('click', 'button', function (event) {  


        var data = table.row($(this).parents('tr')).data();
        rowData = data;
  
        console.log("GET edit DATA", data)        

      });

      
      $(function(){
        $('#exampleModal').on('show.bs.modal', function (event) {

          var button = $(event.relatedTarget);
          var recipient = button.data('whatever');
         
          var data = rowData;
          
          // getEditData
          var modal = $(this);
          modal.find('.modal-title').text('Update data ' + recipient);
          var inputFields = modal.find('.modal-body input');
          var keys = Object.keys(data);
          for (var i = 0; i < inputFields.length; i++) {
            var inputValue = data[keys[i]];
            $(inputFields[i]).val(inputValue);
          }
        });
      });
  


      function editRow_website(id){
        
        

            
        var device_id=document.getElementById("device_id"+id);  
        var name=document.getElementById("name"+id);  
        var group=document.getElementById("group"+id);

        
        let getEditData = {
          "device_id": device_id,
          "email_data": name,
          "address_data": group,

        }

        document.getElementById("#editid input").value = device_id
       

        
      }
      

      $(document).on('click', '.delete-btn', function (event) {  
        var id = $(this).data('id')
        
        console.log("GET DLETE ID", id)

        confirmDelete(id) 
      });

      function deleteData(id) {
        $.ajax({
          url: "http://192.168.0.0:3000/api/product?id="+ id,
          type:'DELETE',
          headers: {
            'Authorization': 'Bearer ' + getToken  
          },
          success: function(response){
            console.log(response);
          }

        }).then(res => console.log("RES", res));  
      }


      function confirmDelete(id) {
        if (confirm("sure to delete this data?")== true) {
          var table = $("#example").DataTable();
          var row = table.row($(this).closest('tr'));
          deleteData(id);

          if (row.length > 0) {
            row.remove().draw();
            console.log("Delete row with id:", id);
          }
        } else{
          none
        }

      }
    });
  </script>
  <script src="script.js"></script>

  <div class ="table-title">
    <div class="row">
      <div class="col-sm-4">
        <!-- <button type="button" class="btn btn-info add-new" onclick="AddRow()"><i class="fa fa-plus"></i>Add New</button> -->
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever=" " onclick="AddRow()">Add New02</button>
      </div>
    </div>
  </div>


  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">device_id:</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group">
              <label for="input_edit_device_id" class="col-form-label">Device ID:</label>
              <input type="text" class="form-control" id="input_edit_device_id">
            </div>
            <div class="form-group">
              <label for="input_edit_name" class="col-form-label">name:</label>
              <input type="text" class="form-control" id="input_edit_name">
            </div>
            
            <!-- Additional form fields -->
            <div class="form-group">
              <label for="field1" class="col-form-label">group:</label>
              <input type="text" class="form-control" id="input_edit_data_group">
            </div>

       


            <!-- End of additional form fields -->
            
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" onclick="save()">Send message</button>
        </div>
      </div>
    </div>
  </div>



  <script>
    function AddRow() {
      const getToken = localStorage.getItem("token")

      var data = {
            "device_id": "string-test01",
            "name": "0",
            "group": "group-1",
            "ip": "192.168.0.111",
            "port": "3000",
            "ipc_enable": "false",
            "ftp_enable": "false"
        }
      $.ajax({
        url : 'http://192.168.0.0:3000/api/product01',
        type : 'post',
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8', 
        data :JSON.stringify(data) , 
        headers: {
          'Authorization': 'Bearer ' + getToken  
        },
        success : function(result) {
          console.log("SUCCESS", result) 
        },
        error:  function(response){
          console.log("ERROR",response);
        }
      });

    }


    function editRow(data) {
      const getToken = localStorage.getItem("token")

      console.log("GET TOKEN", getToken)

      console.log("EDIT=====", data);
      $.ajax({
        url: "http://192.168.0.0:3000/api/product01",   
        type:'PUT',   // aka update or edit
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8', 
        data :JSON.stringify(data) , 
        headers: {
          'Authorization': 'Bearer ' + getToken  
        },
        success: function(response){
          console.log("SUCCESS",response);
        },
        error:  function(response){
          console.log("ERROR",response);
        }
      })
       
      }
    $(function() {
        $('#exampleModal').on('show.bs.modal', function(e) {
          $('.modalTextInput').val('');
          let btn = $(e.relatedTarget); // e.related here is the element that opened the modal, specifically the row button
          let id = btn.data('id'); // this is how you get the of any `data` attribute of an element
          $('.saveEdit').data('id', id); // then pass it to the button inside the modal
        })
      
        $('.saveEdit').on('click', function() {
          let id = $(this).data('id'); // the rest is just the same
          saveNote(id);
          $('#exampleModal').modal('toggle'); // this is to close the modal after clicking the modal button
        })
      })
      
      function saveNote(id) {
        let text = $('.modalTextInput').val();
        $('.recentNote').data('note', text);
        console.log($('.recentNote').data('note'));
        console.log(text + ' --> ' + id);
      }

    
    </script>

  <script>
    var storedItem = localStorage.getItem("storedItem") || [];
    
    function save() {
      var itemValue_device_id = document.getElementById("input_edit_device_id").value || "";
      var itemValue_edit_name = document.getElementById("input_edit_name").value || "";
      var itemValue_data_group = document.getElementById("input_edit_data_group").value || "";


      console.log("itemValue_device_id", itemValue_device_id, typeof(itemValue_device_id));
      console.log("itemValue_edit_name", itemValue_edit_name, typeof(itemValue_edit_name));
      console.log("itemValue_data_group", itemValue_data_group, typeof(itemValue_data_group));


      
      // document.getElementById("input_edit_data_group").val = itemValue;

      let send_Edit_API_Data = {
        device_id:itemValue_device_id,
        name:itemValue_edit_name,
        group: itemValue_data_group,


      }
      console.log("send_Edit_API_Data", send_Edit_API_Data);

      editRow(send_Edit_API_Data)
    }
  </script>
</body>
</html>

I tried this function, but both "edit","add" button comes out empty

      $(function() {
      $('#exampleModal').on('show.bs.modal', function(event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('whatever');
        
        var data = rowData;
        
        var modal = $(this);
        modal.find('.modal-title').text('Update data ' + recipient);
        var inputFields = modal.find('.modal-body input');
        
        if (recipient == ' ') { // Add New02 button clicked, clear form values
          inputFields.val('');
        } else { // Edit button clicked, populate form with existing values
          var keys = Object.keys(data);
          for (var i = 0; i < inputFields.length; i++) {
            var inputValue = data[keys[i]];
            $(inputFields[i]).val(inputValue);
          }
        }
      });
    });

2

Answers


  1. Chosen as BEST ANSWER

    if else with button id is simple way I to deal with this

          $(function() {
          $('#exampleModal').on('show.bs.modal', function(event) {
            var button = $(event.relatedTarget);
            var recipient = button.data('whatever');
            var modal = $(this);
            var data = rowData;
            modal.find('.modal-title').text('Update data ' + recipient);
            var inputFields = modal.find('.modal-body input');
            
            if (button.attr('id') == "AddedNew_Data") {
              inputFields.val("");
            } else {
              var keys = Object.keys(data);
              for (var i = 0; i < inputFields.length; i++) {
                var inputValue = data[keys[i]];
                var inputValue = rowData[keys[i]];
                $(inputFields[i]).val(inputValue);
              }
            }
          });
        });
    
    ```
    
    but still thank all you guys effort and suggestion
    

  2. You can do this:

    $('#id_of_input_to_set_null').val("");
    

    Example:

    $('#input_edit_device_id').val("");
    

    You need to put this inside the function that opens the modal for adding new data.

    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search