1

I have a dynamic input boxes having the following ids, points0, points1,points2 etc. I want to make sure that these input boxes shoould match only numbers. So I used the following code but in console it always shows

TypeError: $(...).val(...) is undefined

So I used the following code. I am looping over input text boxes.

var result = document.getElementsByTagName("input");
for (var j = 0; j < result.length; j++) {
var points = 'Enter a valid point.';
var regex = '/^[A-Za-z!@#></!?\$%\^\&*\)\(+=._-]+$/g';
 if ($("#points" + j).val().match(regex)) {
                    $('#points' + j + ' + span').html('');
                    $('#points' + j).after('<span class="' + errTextboxClass + '" style="color:#e03b3b;">' + points + '</span>');
                    $('#points' + j).focus();
                }
  }

   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

In my Laravel blade I am looping some answers,

 @if($ans)
 @for($j=0;$j<count($ans) ;$j++)
 <input class="form-control " name="points[]" id="points{{$j}}" placeholder="POINTS"  value="<?php echo $ans[$j]['points'];?>">
@endfor
@endif
Oops
  • 1,373
  • 3
  • 16
  • 46

1 Answers1

0

You may want to use a better selector for the input elements. You can use input[id^='points'] for example. This will look for input elements with a the id that starts with points.

Consider the following example:

var results = $("input[id^='points']");
var points = 'Enter a valid point.';
var regex = '/^[A-Za-z!@#></!?\$%\^\&*\)\(+=._-]+$/g';
results.each(function(i, el) {
  if ($(el).val().match(regex)) {
    console.log("Match on #" + $(el).attr("id"));
    $(el).next('span').html('');
    $("<span>", {
      class: "errTextboxClass"
    }).css("color", "#e03b3b;").html(points).insertAfter($(el));
    $(el).focus();
  }
});

Using .each() we can iterate each of the matching elements and test them against the RegEx pattern. You might also consider a different pattern. It looks like you want to allow only numbers, could try:

^[\D]+$

This would match any Non-Digit. If it were me, I would prevent the User from being able to enter non-digits in the field itself using .keypress(). For example:

$(function() {
  $("input[id^='points']").keypress(function(e) {
    console.log(e.which);
    if (e.which !== 46 && (e.which < 48 || e.which > 57)) {
      e.preventDefault();
    }
  });
});
label {
  width: 80px;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label>Points 1</label> <input id="points1" type="text">
</div>
<div>
  <label>Points 2</label> <input id="points2" type="text">
</div>
<div>
  <label>Name</label> <input id="name1" type="text">
</div>

See More:

Twisty
  • 30,304
  • 2
  • 26
  • 45