0

I'm using one dynamic table and form and i create one small validation form my form and that dynamic table validation.. its working but if form is not valid also its submitting.. dont need that.. just want when form is valid that time only form going to submit. otherwise restrict error message wants to shown.. like "this field is required"

Fiddle Here..

FIDDLE HERE..

My sample code is here..

$(document).ready(function() {

  $('#contactForm').validate({
    rules: {
      acctcode: {
        required: true
      },
      accountName: {
        required: true
      },
      narr: {
        required: true
      },
      debit: {
        required: true
      },
      billtype: {
        required: true
      },
      cashactcode: {
        required: true
      }
    },
    submitHandler: function(form) {
      alert('valid form');
      return false;
    }
  });
  $('#cashSub').on('click', function() {
    $('#contactForm').valid();
  });

});


$(document).ready(function() {

  $("#add_Row").on("click", function() {
    var counter = 0;
    var idVal = $('#tab_logic tr:last').find('td:first').html();
    var matches = idVal.match(/\d+/g);
    if (matches != null) {
      counter = Number(matches) + counter + 1;
    }
    var newRow = $("<tr>");
    var cols = "";
    cols += '<td><select class="form-control sel_sel status" id="accountName' + counter + '" name="accountName" required><option>Select cash account</option><option value="1">TDS A/c 1</option><option value="2">TDS A/c 2</option><option value="3">TDS A/c 3</option></select></td>'
    cols += '<td><input type="text" class="form-control required price" name="narr" placeholder="Enter your text here" id="acc_narrat' + counter + '" data-toggle="modal" data-target="#narratModal" onchange="unname(this.id, this.value)"/></td>';

    cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';

    newRow.append(cols);


    var defVal = $("select[name=acctname]").find(":selected").val();
    if (defVal) {
      $("select[name=accountName]").find(`option[value=${defVal}]`).hide();
    }
    $("table.order-list").append(newRow);
    setValCashVal('accountName'.concat(counter));
    bindScript();
    counter++;

  });
  $("table.order-list").on("click", ".ibtnDel", function(_event) {
    $(this).closest("tr").remove();
    evaluateTotal();
  });
});

/* Apend value to all row */
$("#ok_button").on('click', function() {
  let val = $("#cash_text").val();
  $("#pay_narrat, #acc_narrat").val(val);
});
.load {
  border-color: black;
  background-color: plum !important;
}

.load:hover {
  background-color: blue
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<form id="contactForm">

  <input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
  <table class="table table-bordered table-hover order-list" id="tab_logic" style="width:60% !important">

    <tbody>
      <tr id="fst_row">
        <td>
          <select class="form-control sel_sel" id="payacc" name="actname" for="actname">
            <option value="">Select TDS A/c name</option>
            <option value="1">TDS A/c 1</option>
            <option value="2">TDS A/c 2</option>
            <option value="3">TDS A/c 3</option>
          </select>
        </td>
        <td>
          <input type="text" class="form-control required" id="pay_narrat" name="narr" for="narr" data-toggle="modal" data-target="#narratModal" placeholder="Enter your text here" />

        </td>
      </tr>
    </tbody>
  </table>

  <!-- narrtion modal -->

  <div class="modal fade" id="narratModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
          <h4 class="modal-title modal_head" id="myModalLabel">Narration</h4>
        </div>
        <div class="modal-body">
          <label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % [] () - _ . , are allowed in text</label>
          <textarea id="cash_text" class="cash_text" maxlength="200">Enter Here...</textarea>
          <span class="modal_valid">0/200 Characterts entered</span>
        </div>
        <div class="modal-footer narr_footer">
          <button id="ok_button" type="button" class="btn btn-primary cashmodal_btn" data-dismiss="modal">OK</button>
        </div>
      </div>
    </div>
  </div>

</form>
<!-- submit -->
<div class="form-group col-4 vocSub" style="margin-bottom: 0px !important;">
  <div class="col-md-12 cashform_submit" id="">
    <input type="submit" class="btn add-btn submit-btn load cashmainBtn" id="cashSub" th:value="Submit" tabindex="1" value="Submit" />
  </div>
</div>

3
  • Your input type="submit" is not inside the form. Also, when the modal is shown (if you're using a framework) it also will not be inside the form as frameworks (eg jquery-ui/bootstrap) move the modal to the body so that it can shown in the correct place. Commented Nov 15, 2019 at 13:31
  • Html for the submit-button is not inside the form element Commented Nov 15, 2019 at 13:33
  • Yes! if i using inside html same validation is'nt work.. see - jsfiddle.net/joelshah/dw9Lj86s Commented Nov 15, 2019 at 13:36

2 Answers 2

1

There are 2 ways to submit the form. Either including "Submit" button inside the form or dynamically submit the for from jQuery code.

In your case, the first issue is that whenever you add new fields dynamically using Add Row button, it will not apply validation rules to dynamically added fields. You need to apply rules dynamically as I applied in the fiddle.

FYI

$('input.narr').each(function() {
        $(this).rules("add", 
        {
            required: true
        })
});

Temporarily I have disabled the modal which opens up on the click of text fields. Please refer to the fiddle and let me know in case of any issues.

$(document).ready(function() {

  $('#contactForm').validate({
    rules: {
      acctcode: {
        required: true
      },
      accountName: {
        required: true
      },
      narr: {
        required: true
      },
      debit: {
        required: true
      },
      billtype: {
        required: true
      },
      cashactcode: {
        required: true
      }
    }
  });  

});


$(document).ready(function() {
  var counter = 0;
  $("#add_Row").on("click", function() {
    var idVal = $('#tab_logic tr:last').find('td:first').html();
    var matches = idVal.match(/\d+/g);
    
    var newRow = $("<tr>");
    var cols = "";
    cols += '<td><select class="form-control sel_sel status" id="accountName' + counter + '" name="accountName" required><option>Select cash account</option><option value="1">TDS A/c 1</option><option value="2">TDS A/c 2</option><option value="3">TDS A/c 3</option></select></td>'
    cols += '<td><input type="text" class="narr form-control required" name="narr'+ counter + '" placeholder="Enter your text here" id="acc_narrat' + counter + '" /></td>';

    cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';

    newRow.append(cols);


    var defVal = $("select[name=acctname]").find(":selected").val();
    if (defVal) {
      $("select[name=accountName]").find(`option[value=${defVal}]`).hide();
    }
    $("table.order-list").append(newRow);
    
  counter++;
  });
  $('#contactForm').on('submit', function(event) {
  console.log($('.narr'))
            $('.narr').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });
            event.preventDefault();
            if($('#contactForm').validate().form()) {
                alert("validates");
            } else {
                alert("does not validate");
            }
  });
  $('#contactForm').validate();
});
.load {
  border-color: black;
  background-color: plum !important;
}

.load:hover {
  background-color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" crossorigin="anonymous"></script>

<form id="contactForm" method="get" action="">

  <input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
  <table class="table table-bordered table-hover order-list" id="tab_logic" style="width:60% !important">

    <tbody>
      <tr id="fst_row">
        <td>
          <select class="form-control sel_sel" id="payacc" name="actname" for="actname">
            <option value="">Select TDS A/c name</option>
            <option value="1">TDS A/c 1</option>
            <option value="2">TDS A/c 2</option>
            <option value="3">TDS A/c 3</option>
          </select>
        </td>
        <td>
          <input type="text" class="form-control required" id="pay_narrat" name="narr" placeholder="Enter your text here" />

        </td>
      </tr>
    </tbody>
  </table>


<!-- submit -->
<div class="form-group col-4 vocSub" style="margin-bottom: 0px !important;">
  <div class="col-md-12 cashform_submit" id="">
    <input type="submit" class="btn add-btn submit-btn load cashmainBtn" id="cashSub" th:value="Submit" tabindex="1" value="Submit" />
</form>

  </div>
</div>

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

3 Comments

My bad! Corrected now. Please check the fiddle again and let me know if it doesn't work.
It's validate only two rows! if i add more than two rows, its not works..
It's working now. Please check now. There was an issue with the "counter".
0

You first should capture the event that is triggered once you click the submit button, you can do that with jQuery with:

$(document).on('submit', **ID or CLASS or ATTRIBUTE of your FORM**, function(event){
  // Logic here
})

If you return false inside this piece of code, the submit will stop, so

$(document).on('submit', **ID or CLASS or ATTRIBUTE of your FORM**, function(event){
     if(!form_is_not_valid()){
        return false;
     } 
     return true;
})

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.