Cергій Крепкій Cергій Крепкій - 7 months ago 14
HTML Question

max length check not working

Use 'getElementsByname' but it don't helps me. What I'm doing wrong? "isAllowedSymbol" function is working great but not "checkNumbers".

function checkNumbers(this) {
var element = document.getElementsByname('answer')[0];
if (element != null && element.value.length == 10) {
element = element.replace(element, '');
}
}

function isAllowedSymbol(input) {
var value = input.value;
var rep = /[a-zA-Z]/;
var rep2 = /[а-яА-Я]/;

if (rep.test(value)) {
value = value.replace(rep, '');
input.value = value;
if (rep2.test(value)) {
value = value.replace(rep2, '');
input.value = value;
}
}
}


<input type="text" maxlength="10" onkeyup="isAllowedSymbol(this);checkNumbers(this); " placeholder="Enter data" name="answer" "> <br>


I want to get by name,not id,what is my problem? Or may be I can get it only by "id"? Thank you.

Answer

You can not accept "this" as argument reason being it is Unexpected token this Also typo @ getElementsByname. But as you are sending this from the click-handler, you do not need that. You can grab the element using any other argument name than this

function checkNumbers(element) {
  if (element != null && element.value.length == 10) {
    element = element.replace(element, '');
  }
}

function isAllowedSymbol(input) {
  var value = input.value;
  var rep = /[a-zA-Z]/;
  var rep2 = /[а-яА-Я]/;

  if (rep.test(value)) {
    value = value.replace(rep, '');
    input.value = value;
    if (rep2.test(value)) {
      value = value.replace(rep2, '');
      input.value = value;
    }
  }
}
<input type="text" maxlength="10" onkeyup="isAllowedSymbol(this);checkNumbers(this); " placeholder="Enter data" name="answer">