shrddha patel shrddha patel - 26 days ago 7
CSS Question

only write predefined text in textbox using javascript

I want to do in textbox only add predefined text.



<input type="text" class="mytxt" onkeyup="return SplitChar(this.id);">
<script>
function SplitChar(txt) {
var mainval = document.getElementById(txt).value;
var Data = "hello".split('');
var Datas = mainval.split('');
var charLen = mainval;
if (Datas[mainval.length - 1] == Data[charLen.length - 1]) {
return true;
} else {
document.getElementById(txt).value = mainval.substr(0, mainval.length - 1);
alert("Please write as specified example");
return false;
}
}
</script>





in this text box only written "helloo" nothing else
i want to check on keyup event. and whith out use event function

Can anyone give me a suggestion?

Answer Source

Try this code.

Remove this.id in onkeyup="return SplitChar(this.id);" because you aready accessing in JS as var mainvaland add id to input because you accessing its value based on id

 function SplitChar() {
    var mainval = document.getElementById('txt').value;
    var Data = "hello".split('');
    var Datas = mainval.split('');
    var charLen = mainval;
    if (Datas[mainval.length - 1] == Data[charLen.length - 1]) {
      return true;
    } else {
      document.getElementById('txt').value = mainval.substr(0, mainval.length - 1);
      alert("Please write as specified example");
      return false;
    }
  }
<input type="text"  class="mytxt" id="txt" onkeyup="return SplitChar();">