0

Can I add the Jquery Validation to dynamic inputs? I have this sample below where I need it validate just the inputs without the placeholder. I am using keypress to get all the events of a input control. Once the user hits the enter button after I am then clone a div and update the ids. I have this but its not working

function modalValidate() {
    var form = $("#dialogMultipleChoiceGrid");
    form.validate({
        rules: {
            fieldrowItem_1: {
                required: true
            },
        }
    })
}

        $("[id^='fieldrowItem_']").on('keypress', function keyPressHanlder (e) {
            if (e.which === 13) {
                let rowDataChanged = $(this).data();

                    let rowCount = $('[id^=newrowItem_]').length
                    let newrowCount = rowCount + 1;

                    let rowField = $("[id='newrowItem_" + rowCount + "']").clone(true,true);
                    let rowInput = "input[id='fieldrowItem_" + rowCount + "']";                

                    let newrowInput = "fieldrowItem_" + newrowCount;

                    let placeholder = "Row " + newrowCount;

                    rowField = rowField.attr("id", "newrowItem_" + newrowCount + "");
                    rowField.find(rowInput)
                        .attr("id", newrowInput)
                        .attr("placeholder", placeholder)
                        .val('');

                    $("[id='newrowItem_" + rowCount + "']").after(rowField);

                    $(this).attr('data', "1");

                    $(this).off('keypress', keyPressHanlder);
            }
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class='form-group'>
  <div class="col-sm-6 row">
  <label>Rows</label>
  <div class="input-group" id=newrowItem_1>
  <input type='text' id='fieldrowItem_1' class='form-control fieldrowItem' placeholder="Row 1" data-value="0">
  <div class="input-group-addon">
  <span class="input-group-addon"  style="display: none;cursor:pointer;" data-section="admin" onclick="RemoveRow_1()">
  <i class="fa fa-times"></i>
  </span>
  </div>
  </div>                                            
</div>
Sparky
  • 98,165
  • 25
  • 199
  • 285
Jefferson
  • 173
  • 2
  • 12
  • 32
  • https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/checkValidity – Mister Jojo Jan 28 '23 at 05:43
  • I see you failed to use the search function. This question has been asked about 800 times before and some have good answers. Your code does not work because `.validate()` can only be called once to initialize the plugin. Read the documentation. There is a method called `.rules()` that you would use to add rules to new elements each time you dynamically add fields to the form. – Sparky Jan 28 '23 at 19:13

0 Answers0