0

I have used the reference from from this question and I want to achieve exactly what the question asked however for multiple input text fields. I would like to restrict the user to not type further and have used getElementsByClassName instead of getElementById.

HTML

   <td>
<input id="quantity_scroll" cart_id="<?php echo $cart_row['id']; ?>" min="1" type ="number" max="99" value="<?php echo $cart_row['quantity'] ;?>" oninput = "checkLength()"  class="form-control form-quantity" style=" width: 60px;text-align: left;" >
</td>

Javascript

function checkLength(){

var elements = document.getElementsByClassName("form-quantity");
var y;
var ele = elements.length/2;

for(y=0; y < ele; y++){
    var length = elements[y].value.length;

      if(length <= 2){

        return true;
    }else{  
            var value = elements[y].value;
             value = value.substring(0, value.length-1);    
             document.getElementsByClassName("form-quantity")[y].value = value;
        }
    }
}

enter image description here

However the user is restricted only in the first input box and not in the others. I tried different ways however cannot understand why it isn't happening.

rut_0_1
  • 761
  • 1
  • 11
  • 34
  • You could add the `maxlength` attribute to the input? – evolutionxbox Jul 05 '17 at 08:47
  • "the user is restricted only in the first input box" - I'm not sure if I understand this, do you mean you want restriction to all? or just the first field? because seems to me you need to pass `this` to specifically check the field in focus – Qiqo Jul 05 '17 at 08:52
  • Issue is with your loop... `var ele = elements.length/2;` and `for(y=0; y < ele; y++){` this loops only once, Which never checks your second item.. Also your code needs more work because it is not working on one input at a time but rather working on all when ever there is a keystroke in any one input element.. you better make use of the `this` variable within the function and validate only the input element that is triggering the function – Rajshekar Reddy Jul 05 '17 at 08:52
  • I have divided the length by 2 because I believe because there is another input field which is size. This causes the length to double hence I need to divide it by 2. – rut_0_1 Jul 05 '17 at 09:23

1 Answers1

1

Check the below code. It will restrict users to not enter more than 3 digit numbers. You just need to ensure that all your input fields have the same class form-field:

$(".form-field").on('input', function() {
  var enteredVal = $(this).val();
  if (enteredVal.length > 3) {
    $(this).val(enteredVal.substring(0, enteredVal.length - 1));
    console.log('More than 3 characters not allowed.');
    return;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-field' />
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35