Oops
Oops

Reputation: 1413

Validate dynamically appended text box fields-jQuery

I have a dynamic input field that gets appended after a plus button.

enter image description here

second-img

The corresponding id of these fields are answer0, answer1, answer2 and so on. That means after button click the id will be dynamically appended to the text field. Now I want to validate these fields. My validation code is as follows

function showValidation(response) {
var respArray = JSON.parse(response.responseText).errors;
for(var i=0;i<=(Object.keys(respArray).length);i++){
 var optionss= 'Enter Answers.';
 if($("#answer"+i).val()==''){
      $('#answer'+i+' + span').html('');
      $('#answer'+i).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>'); 
      $('#answer'+i).focus();
    }
}
}

I am checking till response error length. But before giving values in these fields, validation works properly(fig 1). But if I enter values for first 2 fields as in the image above, the validation message does not shows for the third field (fig 2). Because at this stage the id is answer2 and the loop 'i' value checks 0 first and next checks 1. So inside loop answer0 and answer1 are having values so the validation stops there. I need to get validation for the next fields too. Thanks in advance.

My HTML and corresponding append function

 <input class="form-control" name="answer0[]" id="answer0" placeholder="OPTION 1">
 <a class="add-option" onclick="AppendOption()"><img src="{{asset('admin/images/icn-add-option.png')}}" alt=""></a>


   function AppendOption(){
    var k=1;
    $('#appendOption').append('<div class="form-group row"><div class="col-md-4"><input class="form-control" name="answer0[]" id="answer'+k+'" placeholder="OPTION" ></div></div>');
    k++;
     }

Upvotes: 0

Views: 543

Answers (3)

Oops
Oops

Reputation: 1413

I tried to display the error messages inside an input array loop and I got the answer.

    var result = document.getElementsByTagName("input");
    var optionss= 'Enter Answers.';
    for (var j = 0; j < result.length; j++) {
     if($("#answer"+j).val()==''){
      $('#answer'+j+' + span').html('');
      $('#answer'+j).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>'); 
      $('#answer'+j).focus();
    }

Upvotes: 0

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

In your AppendOption function, you set k=1 This is an invalid option once you reach the third entry (option 2). You should instead detect that, better yet still make it context sensitive when it executes. I did this by adding a answer-item class and detecting how many we have and using that number instead.

I wrapped all this in a <div id="options-container"> so I would have a place to hook the event handler (delegateTarget) https://api.jquery.com/event.delegateTarget/

I would not have used an ID here and instead used classes, but that is not part of the question but more rather the cause of it.

$('.options-container').on('click','.add-option',function(event){
  let k= $(event.delegateTarget).find('.answer-item').length;
  $(event.delegateTarget).append('<div class="form-group row"><div class="col-md-4"><input class="form-control answer-item" name="answer0[]" id="answer' + k + '" placeholder="OPTION" ></div></div>');
});

function showValidation(response) {
  var respArray = JSON.parse(response.responseText).errors;
  for (var i = 0; i <= (Object.keys(respArray).length); i++) {
    var optionss = 'Enter Answers.';
    if ($("#answer" + i).val() == '') {
      $('#answer' + i + ' + span').html('');
      $('#answer' + i).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss + '</span>');
      $('#answer' + i).focus();
    }
  }
}
<div id="options-container">
  <input class="form-control answer-item" name="answer0[]" id="answer0" placeholder="OPTION 1">
  <a class="add-option"><img src="{{asset('admin/images/icn-add-option.png')}}" alt=""></a>
</div>

Upvotes: 1

Insomnia88
Insomnia88

Reputation: 368

If the fields are required you should mark them as required otherwise you validate every field. In your case another way for validating could look like this

function showValidation(response) {
    var respArray = JSON.parse(response.responseText).errors;
    $('.form-group input.form-control').each(function(){
        if ($(this).val() == '') {
            $(this).next('span').html('');
            $(this).after('<span class="' + errTextboxClass + '" style="color:#e03b3b">' + optionss+ '</span>');
            $(this).focus();
        }
    });
}

Since I don't know how and where the showValidation() is called I can't improve it further.

Upvotes: 1

Related Questions