0

Im trying to create a dynamic text field where user can press an add button to insert another entry. I also created a javascript code to check whether the user input is available or not ( similar to checking username is available or not).

However, since my form is a dynamic form, the checking part will only checks for the first textfield. If I click add, the second textfield wont be 'validated'. Below is my jsfiddle or my html and javascript code.

UPDATE:

I think the problem lies on the javascript because it only runs on the first default textfield row. If I added a new row and insert a value and check on network on developers tool, my check.php doesnt run. How do I make the javascript code to rerun on every gamecenter[] count?

$(document).ready(function() {
  $('select').on('change', function() {

    var number = $('#number').val();
    var gamecenter = $('#gamecenter').val();

    $.ajax({
      url: 'check.php',
      method: "POST",
      data: {
        number: number,
        gamecenter: gamecenter
      },
      success: function(data) {
        if (data == '0') {
          $('#availability').html('<span class="text-danger">Number not available</span>');
          $('#proceed').attr("disabled", true);
          $('#number').addClass('validation-error');
        } else {
          $('#availability').html('<span class="text-success">Number Available</span>');
          $('#proceed').attr("disabled", false);
          $('#number').removeClass('validation-error');
          // $('#number').addClass('validation-success');

        }
      }
    })

  });
});


$(document).ready(function() {
  $('#number').blur(function() {

    var number = $('#number').val();
    var gamecenter = $('#gamecenter').val();

    $.ajax({
      url: 'check.php',
      method: "POST",
      data: {
        number: number,
        gamecenter: gamecenter
      },
      success: function(data) {
        if (data == '0') {
          $('#availability').html('<span class="text-danger">Number not available</span>');
          $('#proceed').attr("disabled", true);
          $('#number').addClass('validation-error');
        } else {
          $('#availability').html('<span class="text-success">Number Available</span>');
          $('#proceed').attr("disabled", false);
          $('#number').removeClass('validation-error');
        }
      }
    })

  });
});



$(document).ready(function() {

  $(document).on('click', '.add', function() {
    var html = '';
    html += '<tr>';
    html += '<td> <input type="number" min="0" max="100" name="number[]" id="number" value="" class="form-control item_name number" required autocomplete="off" maxlength="3" /><span id="availability"></span></td>';
    html += '<td><input type="text" name="price[]" id="price"  class="form-control item_quantity price" required autocomplete="off" /></td>';
    html += '<td><select name="gamecenter[]" id="gamecenter" class="form-control item_unit gamecenter" required><option value="">Select Unit</option><option value="Damacai">Damacai</option><option value="Magnum">Magnum</option><option value="Toto">Toto</option></select></td>';
    html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
    $('#item_table').append(html);
  });

  $(document).on('click', '.remove', function() {
    $(this).closest('tr').remove();
  });

  $('#insert_form').on('submit', function(event) {
    event.preventDefault();
    var error = '';
    $('.number').each(function() {
      var count = 1;
      if ($(this).val() == '') {
        error += "<p>Enter Item Name at " + count + " Row</p>";
        return false;
      }
      count = count + 1;
    });

    $('.price').each(function() {
      var count = 1;
      if ($(this).val() == '') {
        error += "<p>Enter Item Quantity at " + count + " Row</p>";
        return false;
      }
      count = count + 1;
    });

    $('.gamecenter').each(function() {
      var count = 1;
      if ($(this).val() == '') {
        error += "<p>Select Unit at " + count + " Row</p>";
        return false;
      }
      count = count + 1;
    });

    var form_data = $(this).serialize();

    if (error == '') {
      $.ajax({
        url: "insert.php",
        method: "POST",
        data: form_data,
        success: function(data) {
          $(document.body).append(data);

        }

      });
    } else {
      $('#error').html('<div class="alert alert-danger">' + error + '</div>');
    }
  });

});
body {
  margin: 0;
  padding: 0;
  background-color: #f1f1f1;
}

.box {
  width: 800px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  margin-top: 36px;
}

.validation-error {
  border: 1px solid #e80c4d;
}

.validation-success {
  border: 1px solid #008000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="container box">
  <table class="table table-bordered" id="item_table">
    <tr>
      <th>2D Number</th>
      <th>Price (RM)</th>
      <th>Game Center</th>
      <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
    </tr>

    <tr>
      <td>
        <input type="number" min="0" max="100" name="number[]" id="number" value="" class="form-control item_name" required autocomplete="off" maxlength="3" /><span id="availability"></span>
      </td>
      <td>
        <input type="text" name="price[]" id="price" class="form-control item_quantity" required autocomplete="off" />
      </td>
      <td>
        <select name="gamecenter[]" id="gamecenter" class="form-control item_unit" required><option value="">Select Unit</option><option value="Damacai">Damacai</option><option value="Magnum">Magnum</option><option value="Toto">Toto</option></select>
      </td>
      <td>
        <button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button>
      </td>
    </tr>

  </table>

  <div align="center">
    <input type="submit" name="proceed" id="proceed" class="btn btn-info" value="Check Number" />
  </div>
  </form>

and my Check.php code.

   <?php  
   //check.php  
   $connect = mysqli_connect("localhost", "root", "", "2d_system"); 
   if(isset($_POST["number"]) && ($_POST["gamecenter"]))
   {

   $number = mysqli_real_escape_string($connect, $_POST["number"]);
   $gamecenter = mysqli_real_escape_string($connect, $_POST["gamecenter"]);
   $query = "SELECT * FROM number_availability WHERE Number = '".$number."' 
   AND GameCenter = '".$gamecenter."' AND Availability != 0";
   $result = mysqli_query($connect, $query);
   echo mysqli_num_rows($result);
   }

   ?>

Any tips/advice/help would be much appreciated! Thanks in advance.

3
  • ids must be unique. you cannot have a form that generates inputs that will all have the same id. also, please try to minimize your examples. i for one would prefer not to have to read 100 lines of code just to figure out whats happening in your script. read how to make an mcve. Commented Feb 18, 2018 at 5:22
  • Forgive me, ill comply to mcve in the future. So, what exactly are you suggesting? I do not understand. Commented Feb 18, 2018 at 5:34
  • between my comment and the answer given by G_S you should have all the info you need. you are creating elements with id's instead of classes. i really don't know how to be more clear without writing the code for you. Commented Feb 18, 2018 at 5:38

1 Answer 1

1

You are using a class $('.number') to check for condition. But you are not adding a class when adding a new row.

HTML file

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src='./testjsfile.js'></script>
<form id='insert_form'>
<div class="container box">
  <table class="table table-bordered" id="item_table">
    <tr>
      <th>2D Number</th>
      <th>Price (RM)</th>
      <th>Game Center</th>
      <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
    </tr>

    <tr>
      <td>
        <input type="number"  name="number[]" id="number" value="" class="form-control item_name" required autocomplete="off" maxlength="3" /><span id="availability"></span>
      </td>
      <td>
        <input type="text" name="price[]" id="price" class="form-control item_quantity"  autocomplete="off" />
      </td>
      <td>
        <select name="gamecenter[]" id="gamecenter" class="form-control item_unit" ><option value="">Select Unit</option><option value="Damacai">Damacai</option><option value="Magnum">Magnum</option><option value="Toto">Toto</option></select>
      </td>
      <td>
        <button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button>
      </td>
    </tr>

  </table>

  <div align="center">
    <input type="submit" name="proceed" id="proceed" class="btn btn-info" value="Check Number" />
  </div>
  <div id='error'></div>
  </form>

and JS file

$(document).ready(function() {
    $('select').on('change', function() {

      var number = $('#number').val();
      var gamecenter = $('#gamecenter').val();

      $.ajax({
        url: 'check.php',
        method: "POST",
        data: {
          number: number,
          gamecenter: gamecenter
        },
        success: function(data) {
          if (data == '0') {
            $('#availability').html('<span class="text-danger">Number not available</span>');
            $('#proceed').attr("disabled", true);
            $('#number').addClass('validation-error');
          } else {
            $('#availability').html('<span class="text-success">Number Available</span>');
            $('#proceed').attr("disabled", false);
            $('#number').removeClass('validation-error');
            // $('#number').addClass('validation-success');

          }
        }
      })

    });
  });


  $(document).ready(function() {
    $('#number').blur(function() {

      var number = $('#number').val();
      var gamecenter = $('#gamecenter').val();

      $.ajax({
        url: 'check.php',
        method: "POST",
        data: {
          number: number,
          gamecenter: gamecenter
        },
        success: function(data) {
          if (data == '0') {
            $('#availability').html('<span class="text-danger">Number not available</span>');
            $('#proceed').attr("disabled", true);
            $('#number').addClass('validation-error');
          } else {
            $('#availability').html('<span class="text-success">Number Available</span>');
            $('#proceed').attr("disabled", false);
            $('#number').removeClass('validation-error');
          }
        }
      })

    });
  });



  $(document).ready(function() {

    $(document).on('click', '.add', function() {
      var html = '';
      html += '<tr>';
      html += '<td> <input type="number" min="0" max="100" name="number[]" id="number" value="" class="form-control item_name number"  autocomplete="off" maxlength="3" /><span id="availability"></span></td>';
      html += '<td><input type="text" name="price[]" id="price"  class="form-control item_quantity price" autocomplete="off" /></td>';
      html += '<td><select name="gamecenter[]" id="gamecenter" class="form-control item_unit gamecenter"><option value="">Select Unit</option><option value="Damacai">Damacai</option><option value="Magnum">Magnum</option><option value="Toto">Toto</option></select></td>';
      html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
      $('#item_table').append(html);
    });

    $(document).on('click', '.remove', function() {
      $(this).closest('tr').remove();
    });

    $('#insert_form').on('submit', function(event) {
        debugger
      event.preventDefault();
      var error = '';
      $('.number').each(function() {
        var count = 1;
        if ($(this).val() == '') {
          error += "<p>Enter Item Name at " + count + " Row</p>";
          return false;
        }
        count = count + 1;
      });

      $('.price').each(function() {
        var count = 1;
        if ($(this).val() == '') {
          error += "<p>Enter Item Quantity at " + count + " Row</p>";
          return false;
        }
        count = count + 1;
      });

      $('.gamecenter').each(function() {
        var count = 1;
        if ($(this).val() == '') {
          error += "<p>Select Unit at " + count + " Row</p>";
          return false;
        }
        count = count + 1;
      });

      var form_data = $(this).serialize();

      if (error == '') {
        $.ajax({
          url: "insert.php",
          method: "POST",
          data: form_data,
          success: function(data) {
            $(document.body).append(data);

          }

        });
      } else {
        $('#error').html('<div class="alert alert-danger">' + error + '</div>');
      }
    });

  });
Sign up to request clarification or add additional context in comments.

12 Comments

What do you mean by not adding a class when adding a new row?
in $(document).on('click', ' ..... , looks like you are adding new row. Here you are adding different HTML elements. I hope you should add number class also because you are using .number for checking empty condition
How do I add the class, on $(document).on('click', '.add', function()? I really do not know the syntax. Im sorry for my lack of understanding/knowledge
Updated html code. class="form-control item_name number" I added a number class as above. Still I am not sure if thats the only issue. Check by adding it
Ive tried like u suggested, but it still only validate/check the first default row.
|

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.