0
votes

I have to clear selectize input after submit, but it gives me this error message:

Cannot read property 'clear' of undefined

This is what I have so far:

  1. GET $_POST value, nothing is wrong with this.
   <?php
       $autoclear = "0";
       if (isset($_POST['autoClear']))$autoclear = $_POST['autoClear'];
   ?>
  1. My HTML Form, also nothing wrong with this.
<form method="post" action="">
<input type="checkbox" id="autoClear" name="autoClear" value="1" <?php if ($autoclear == '1') echo 'checked'; ?>>
  <select id="client" name="client" class="client selectize" >
    <option>
      ...
      ...
    </option>
  </select>
<!-- OTHER INPUTS, IRRELEVANT -->
<input type="submit" name="submitBtn" id="submitBtn" class="submitBtn btn-info" value="Submit">

</form>
  1. This is the problem. It seems like the HTML <select id="client" .... </select> must load first before able to call selectize .clear() function. However, since PHP runs in server side so it will print it out, and maybe that caused the problem?
<script>
   function clearSelectize(){

      // Clear Selectize [ERROR]
      $('#client')[0].selectize.clear();
   }

</script>

<?php 
      if ($autoclear == '1'){
         echo "<script>clearSelectize(); </script>";
      }
?>

What I initially did: simply reload the page.

<script>window.location.href = 'page.php'; </script>

But this will clear ALL the inputs, so I have to find a way to clear ONLY selectize input.

Update: Solution#1

<script type="text/javascript">
     $(document).ready(function () {
         <?php
             if ($autoclear == '1'){
                 echo "$('.car.selectize')[0].selectize.clear();";
             }
         ?>
     }
</script>

This works for me, thanks. If anyone has a better way/solution, please let me know.

Any advice/suggestion is very much appreciated! Thanks!

2

2 Answers

0
votes

Since you have to make sure that selectize() has been initialized, using $('document').ready(function(){}); will do the job.

Inside it, you can put your PHP conditions, works after submit:

<script type="text/javascript">
     $(document).ready(function () {
         <?php
             if ($autoclear == '1'){
                 echo "$('.car.selectize')[0].selectize.clear();";
             }
         ?>
     }
</script>
-1
votes

There is no such selector in jquery

$(".classname.classname") // is wrong
// use space multi class 
$(".classname .classname") // is correct 
// your code is wrong 
 $('.client.selectize')[0].selectize.clear();