Search code examples
ajaxcodeignitercodeigniter-3

Duplicate validation (Number) and show an error message


I have a function where I can add rows using my button. My target is when the user enters a number that is already on the database, the alert will pop up or any error messages that will say "The number/s you entered is/are already used, please use another number"**. Is there a way where I can make it work? I provided my screenshot and my codes below. Thank you

enter image description here

Views:

    <table class="table table-bordered" border="1" id="applicanttable">
      <thead>
        <tr>
        </tr>
      </thead>
      <tbody>
        <div class="row">
          <tr>
            <th>#</th>
            <th>Light</th>
    
            <th>Action</th>
          </tr>
          <tr id="row_0">
            <td>
              <input id="#" name="#" class="auto_num" type="text" value="1" readonly />
            </td>
            <td class="labelcell">
              <input value="" class="form" name="lightBand1" placeholder=""   id="lightBand1"/>
        <span id="email_result"></span>
            </td>
         
            <td class="labelcell">
              <input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
            </td>
          </tr>
        </div>
      </tbody>
    
    
      <tfoot>
        <tr>
        </tr>
        <tr>
          <button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
        </tr>
      </tfoot>
    </table>

script:

   $("#addrow").on('click', function() {
    
      let rowIndex = $('.auto_num').length + 1;
      let rowIndexx = $('.auto_num').length + 1;
    
      var newRow = '<tr><td><input class="auto_num"  type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
        '<td><input name="lightBand'+rowIndex+'" id="lightBand1"  value="" class="form"  type="number"  /></td>"' +
                            ' <span id="email_result"></span>' +
     
        '<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
    
      $("#applicanttable > tbody > tr:last").after(newRow);
    
    
    });

ajax:

  $(document).ready(function(){  
      $('#lightBand1').change(function(){  
           var lightBand1 = $('#lightBand1').val();  
           if(lightBand1 != '')  
           {  
                $.ajax({  
                     url:"<?php echo base_url(); ?>participant/check_number_avalibility",  
                     method:"POST",  
                     data:{lightBand1:lightBand1},  
                     success:function(data){  
                          $('#email_result').html(data);  
                     }  
                });  
           }  
      });  
 });  

Controller:

  function check_number_avalibility()
    {
        if(!filter_var($_POST["lightBand1"], FILTER_VALIDATE_INT))
        {
            echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> Invalid LightBand</span></label>';
        }
        else
        {
            $this->load->model("Participant_repository");
            if($this->participants->is_number_available($_POST["lightBand1"]))
            {
                echo '<label class="text-danger"><span class="glyphicon glyphicon-remove"></span> LightBand is already registered</label>';
            }
            else
            {
                echo '<label class="text-success"><span class="glyphicon glyphicon-ok"></span> LightBand Available</label>';
            }
        }  
    }

Model:

  function is_number_available($lightBand)
{
    $this->db->where('lightBand', $lightBand);
    $query = $this->db->get("entry");
    if($query->num_rows() > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}  

**

$("#addrow").on('click', function() {

  let rowIndex = $('.auto_num').length + 1;
  let rowIndexx = $('.auto_num').length + 1;

  var newRow = '<tr><td><input class="auto_num"  type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
    '<td><input name="light' + rowIndex + '" placeholder="duplicate validation here" id="auto"  value="" class="form"  type="number"  /></td>"' +
 
    '<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';

  $("#applicanttable > tbody > tr:last").after(newRow);


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
  <thead>
    <tr>
    </tr>
  </thead>
  <tbody>
    <div class="row">
      <tr>
        <th>#</th>
        <th>Light</th>

        <th>Action</th>
      </tr>
      <tr id="row_0">
        <td>
          <input id="#" name="#" class="auto_num" type="text" value="1" readonly />
        </td>
        <td class="labelcell">
          <input value="" class="hehe form-control" name="light1" placeholder="duplicate validation here" required id="auto" />
        </td>
     
        <td class="labelcell">
          <input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
        </td>
      </tr>
    </div>
  </tbody>


  <tfoot>
    <tr>
    </tr>
    <tr>
      <button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
    </tr>
  </tfoot>
</table>

**


Solution

  • As your input are dynamically generated you need bind it with static element so change your event handler like this $(document).on('change', 'input[name*=lightBand]', function() {..}) .Then , use $(this).val() to get value of input where change has occurred and pass same to your ajax .

    In your current jquery code you have many duplicate ids so change them to class . Also , add class email_result to your span tag currrently you have id here and <span class="email_result"></span> is outside td tag put that inside td tag .

    Updated jquery code:

    $(document).on('change', 'input[name*=lightBand]', function() {
      var lightBand1 = $(this).val(); //get value
      var selector = $(this)//save slector
      if (lightBand1 != '') {
        $.ajax({
          url: "<?php echo base_url(); ?>participant/check_number_avalibility",
          method: "POST",
          data: {
            lightBand1: lightBand1
          },
          success: function(data) {
            selector.next('.email_result').html(data);//use next here ..
          }
        });
      }
    });
    

    Quick Demo :

    $("#addrow").on('click', function() {
    
      let rowIndex = $('.auto_num').length + 1;
      let rowIndexx = $('.auto_num').length + 1;
    
      var newRow = '<tr><td><input class="auto_num"  type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
        '<td><input name="lightBand' + rowIndex + '"  value="" class="form"  type="number"  /> <span class="email_result"></span></td>"' +
    
        '<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
    
      $("#applicanttable > tbody > tr:last").after(newRow);
    
    
    });
    
    
    
    $(document).on('change', 'input[name*=lightBand]', function() {
    
      var lightBand1 = $(this).val(); //get value
      var selector = $(this) //save slector
      selector.next('.email_result').html("") //empty previous error
      if (lightBand1 != '') {
        /*$.ajax({
          url: "<?php echo base_url(); ?>participant/check_number_avalibility",
          method: "POST",
          data: {
            lightBand1: lightBand1
          },
          success: function(data) {*/
        selector.next('.email_result').html("NOT GOOD"); //use next here ..
        /* }
        });*/
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <table class="table table-bordered" border="1" id="applicanttable">
      <thead>
        <tr>
        </tr>
      </thead>
      <tbody>
        <div class="row">
          <tr>
            <th>#</th>
            <th>Light</th>
    
            <th>Action</th>
          </tr>
          <tr id="row_0">
            <td>
              <input id="#" name="#" class="auto_num" type="text" value="1" readonly />
            </td>
            <td class="labelcell">
              <input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
              <span class="email_result"></span>
            </td>
    
            <td class="labelcell">
              <input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
            </td>
          </tr>
        </div>
      </tbody>
    
    
      <tfoot>
        <tr>
        </tr>
        <tr>
          <button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
        </tr>
      </tfoot>
    </table>