0

I am using Datatables in my application (Bookstore created in laravel/vuejs) and I would like my search box to be outside of the table. the problem which I am facing is that the search box is not searching the data until I refresh/reload the page 1 or 2 times.

any kind of help will be highly appreciated.

Javascript code is below

$(document).ready(function() {
  var tables = $("#datatable-fixed-header30").DataTable({
    paging: false,
    dom: "t"
  });
  // $(".dataTables_filter").hide();
  $("#bookSearch").keyup(function() {
    tables.search($(this).val()).draw();
  });
});

Full Code in the vue page is like below

<template>
  <div class="container">
    <div class="col-md-12 col-sm-12 col-xs-12" v-for="User1 in Users.data" v-bind:key="User1.id">
      <div class="x_panel" v-if="User1.type=='admin'">
        <div class="x_content">
          <div
            id="datatable-buttons_wrapper"
            class="dataTables_wrapper form-inline dt-bootstrap no-footer"
          >
            <div class="dt-buttons btn-group">
              <button
                class="btn btn-success buttons-copy buttons-html5 btn-sm"
                tabindex="0"
                aria-controls="datatable-buttons"
                @click="newModal"
              >ثبت کاربرد جدید</button>
            </div>

            <!-- /.row -->
            <div class="row">
              <div class="col-lg-6" style="margin-top:-31px;float:left;margin-left:-213px;">
                <div class="input-group">
                  <span class="input-group-btn">
                    <button class="btn btn-info btn-flat" type="button">
                      <i class="fa fa-search"></i>
                    </button>
                  </span>
                  <input type="text" class="form-control" id="bookSearch" placeholder="لټون..." />
                </div>
                <!-- /input-group -->
              </div>
              <div class="col-sm-12">
                <table
                  id="datatable-fixed-header30"
                  class="table table-striped table-bordered dataTable no-footer"
                  role="grid"
                  aria-describedby="datatable-fixed-header_info"
                >
                  <thead>
                    <tr role="row">
                      <th style="width:1%">
                        <input type="checkbox" @click="selectAll" v-model="allSelected" />
                      </th>
                      <th
                        class="sorting"
                        tabindex="0"
                        aria-controls="datatable-buttons"
                        rowspan="1"
                        colspan="1"
                        aria-label="کود: activate to sort column ascending"
                      >کود</th>
                      <th
                        class="sorting_asc"
                        tabindex="0"
                        aria-controls="datatable-buttons"
                        rowspan="1"
                        colspan="1"
                        aria-sort="ascending"
                        aria-label="نام: activate to sort column descending"
                      >نام</th>

                      <th
                        class="sorting"
                        tabindex="0"
                        aria-controls="datatable-buttons"
                        rowspan="1"
                        colspan="1"
                        aria-label=" آدرس الکترونکی: activate to sort column ascending"
                      >آدرس الکترونکی</th>
                      <th
                        class="sorting"
                        tabindex="0"
                        aria-controls="datatable-buttons"
                        rowspan="1"
                        colspan="1"
                        aria-label=" : activate to sort column ascending"
                      >نوعیت کاربرد</th>
                      <th
                        class="sorting"
                        tabindex="0"
                        aria-controls="datatable-buttons"
                        rowspan="1"
                        colspan="1"
                        aria-label=" : activate to sort column ascending"
                      >تاریخ ورود</th>
                      <th
                        class="sorting"
                        tabindex="0"
                        aria-controls="datatable-buttons"
                        rowspan="1"
                        colspan="1"
                        aria-label=" تنظیمات : activate to sort column ascending"
                      >تنظیمات</th>
                    </tr>
                  </thead>

                  <tbody>
                    <tr
                      role="row"
                      class="odd"
                      v-if="Users.data!=undefined && Users.data.length == 0 || Users.data!=undefined && Users.data.length=='' "
                    >
                      <td colspan="7" align="center" :v-show="hidebutton=false">
                        <p class="text-center alert alert-danger">هیڅ مورد نشته</p>
                      </td>
                    </tr>
                    <tr
                      role="row"
                      class="even"
                      v-else
                      v-show="hidebutton=true"
                      v-for="User in Users.data"
                      v-bind:key="User.id"
                    >
                      <td>
                        <div class="custom-control custom-checkbox">
                          <input
                            class="form-check-input"
                            type="checkbox"
                            :value="User.id"
                            v-model="checkedRows"
                            id="chekboxs"
                          />

                          <label class="form-check-label"></label>
                        </div>
                      </td>
                      <td>{{User.id}}</td>
                      <td>{{User.name}}</td>
                      <td>{{User.email}}</td>
                      <td>
                        <span class="tag tag-success">{{User.type}}</span>
                      </td>

                      <td>{{User.created_at|mydate}}</td>

                      <td>
                        <a href="#" class="btn btn-info btn-xs" @click="editModal(User)">
                          <i class="fa fa-pencil"></i> ویرایش
                        </a>
                        <a
                          v-if="User.type !='admin'"
                          href="#"
                          class="btn btn-danger btn-xs"
                          @click="deleteUser(User.id)"
                        >
                          <i class="fa fa-trash-o"></i> حذف
                        </a>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="card-footer">
              <pagination :data="Users" @pagination-change-page="getResults"></pagination>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  components: {
  },

  data() {
    return {
      color: "#59c7f9",
      isLoading: false,
      fullPage: true,
      hidebutton: true,
      color: "blue",
      editMode: false,
      Users: {},
      selected: [],
      allSelected: false,
      checkedRows: [],
      data: [],
      url: "api/getAllusers",
      // selectAll: false,
      form: new Form({
        id: "",
        name: "",
        email: "",
        password: "",
        type: "",
        bio: "",
        photo: ""
      })
    };
  },
  computed: {},
  methods: {
    selectAll: function() {
      this.checkedRows = [];

      if (!this.allSelected) {
        for (user in this.data) {
          this.checkedRows.push(this.data[user].id);
        }
      }
    },

    doAjax() {
      this.isLoading = true;
      this.color = "blue";
      // simulate AJAX
      setTimeout(() => {
        this.isLoading = false;
      }, 1000);
    },
    onCancel() {
      console.log("User cancelled the loader.");
    },
    refrash: function() {
      $("#addNew").modal("hide");
    },
    loadallUsers() {
      axios.get("api/user").then(({ data }) => (this.Users = data));
    },
    getResults(page = 1) {
      this.isLoading = true;
      this.color = "blue";
      // simulate AJAX
      setTimeout(() => {
        this.isLoading = false;
      }, 500);
      axios
        .get("api/user?page=" + page)
        .then(response => {
          this.Users = response.data;
        })

        .then(
          function(response) {
            this.Users = response.data.data;
          }.bind(this)
        );
    },

    loadUsers() {
      if (this.$gate.isAdmin()) {
        this.$Progress.start();
        axios.get("api/user").then(({ data }) => (this.Users = data));

        axios.get("api/getAllusers").then(({ data }) => (this.data = data));
        this.$Progress.finish();
      }
    },

    createUser() {
      if (this.form.name == "") {
        toast.fire({
          type: "warning",
          icon: "warning",
          html: "<h5>نام لازم است.</h5>"
        });
      } else if (this.form.email == "") {
        toast.fire({
          type: "warning",
          icon: "warning",
          html: "<h5> آدرس الکترونکی لازم است.</h5>"
        });
      } else if (this.form.password == "") {
        toast.fire({
          type: "warning",
          icon: "warning",
          html: "<h5>  رمز لازم است.</h5>"
        });
      } else if (this.form.type == "") {
        toast.fire({
          type: "warning",
          icon: "warning",
          html: "<h5>  نوعیت کاربردد لازم است.</h5>"
        });
      } else {
        this.form
          .post("api/user")
          .then(() => {
            //    the below function will be use to reload the page

            //   this.$emit("refreshPage");
            $("#addNew").modal("hide");
            toast.fire({
              icon: "success",
              type: "success",
              html: "<h5> کاربردد موافقانه اجاد گردید</h5>"
            });
            Fire.$emit("refreshPage");
            this.form.reset();
            //   this.$Progress.finish();
          })
          .catch(er => {
            console.log(er);
          });
      }
    }
  },

  created() {
    this.loadUsers();
    // load the page after 3 secound
    Fire.$on("refreshPage", () => {
      this.loadUsers();
    });
  }
};
$(document).ready(function() {
  var tables = $("#datatable-fixed-header30").DataTable({
    paging: false,
    dom: "t"
  });
  // $(".dataTables_filter").hide();
  $("#bookSearch").keyup(function() {
    tables.search($(this).val()).draw();
  });
});
</script>
5
  • You can fire a method on database to force it to get new data by provided query from server. Read datatable docs for finding method. Commented Mar 23, 2020 at 11:16
  • 1
    600 lines of code might be a bit much, try cutting it down so only the essentials are present for the question, that way it's easier to help you. Commented Mar 23, 2020 at 11:19
  • how? can you please guide me Commented Mar 23, 2020 at 11:30
  • It is possible you are attaching event handler too early. Try attaching your handler as follows: $(document).on('keyup', '#bookSearch', function() { /* skipped */ } Commented Mar 23, 2020 at 15:00
  • I found the solution but I declared** var tables** twice is there any other?$(document).ready(function() { var tables = $("#datatable-fixed-header30").DataTable({ retrieve: true, paging: false, dom: "t" }); }); $(document).on("keyup", "#bookSearch", function() { var tables = $("#datatable-fixed-header30").DataTable({ retrieve: true, paging: false, dom: "t" }); tables.search($(this).val()).draw(); }); Commented Mar 23, 2020 at 15:29

1 Answer 1

1

The following approach will allow you to use a search box outside of the table. You should be able to adapt this to your specific code.

My data is in a table called "animals":

<table id="animals" class="display dataTable cell-border" style="width:100%">
...
</table>

1) Set up the search field:

<div id="external_filter" class="dataTables_filter" style="margin: 20px 0;">
  <label>External Search:
    <input id="external_search" type="search" class="" placeholder="" aria-controls="animals">
  </label>
</div>

In this example, I use the same class (dataTables_filter) as the original filter box - you can use whatever you want.

2) Define a basic DataTable:

This is the minimum definition needed to show the technique - you can add all your extra controls, as you need:

$(document).ready(function() {

  var table = $('#animals').DataTable({
    "initComplete": function(settings, json) {
      $('#animals_filter').remove();
    }
  });

  $('#external_filter input').off().keyup(function () {
      table.search(this.value).draw();
  });

});

The initComplete function is used to hide the original search box. We want searching to still be enabled, so we can't use "searching": false.

The $('#external_filter input') code handles searching for you. The data you enter into the search box is captured by this.value and is passed to the table's search functionality.

The web page looks like this:

enter image description here

The overall code is as follows:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>External Search Box</title>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>

<body>

  <div style="margin: 20px;">

  <div id="external_filter" class="dataTables_filter" style="margin: 20px 0;">
    <label>External Search:
      <input id="external_search" type="search" class="" placeholder="" aria-controls="animals">
    </label>
  </div>

  <table id="animals" class="display dataTable cell-border" style="width:100%">
    <thead>
      <tr><th>Animal</th><th>Collective Noun</th><th>Language</th></tr>
    </thead>
    <tbody>
      <tr><td>antelopes</td><td>herd</td><td>English</td></tr>
      <tr><td>elephants</td><td>herd</td><td>English</td></tr>
      <tr><td>éléphants</td><td>troupeau</td><td>French</td></tr>
      <tr><td>Hounds</td><td>pack</td><td>English</td></tr>
      <tr><td>kittens</td><td>kindle</td><td>English</td></tr>
      <tr><td>lions</td><td>pride</td><td>English</td></tr>
      <tr><td>pingouins</td><td>colonie</td><td>French</td></tr>
      <tr><td>ravens</td><td>unkindness</td><td>English</td></tr>
      <tr><td>whales</td><td>pod</td><td>English</td></tr>
      <tr><td>zebras</td><td>herd</td><td>English</td></tr>
    </tbody>
  </table>

  </div>

  <script type="text/javascript">

    $(document).ready(function() {

      var table = $('#animals').DataTable({
        "initComplete": function(settings, json) {
          $('#animals_filter').remove();
        }
      });

      $('#external_filter input').off().keyup(function () {
          table.search(this.value).draw();
      });

    });
  </script>

</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.