0
How can I set a textbox to only accept Letters in JavaScript?
17 Réponses
+ 3
you can do this with JQuery like that :
$(document).ready(function(){
$("#YOURTEXTBOXID").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
});
in this way you use the ascii codes to work only with letters and white spaces
+ 3
I recommend placing JavaScript at the end of <body> like this:
<html>
<head>
</head>
<body>
<!-- html code here -->
<script>
//JavaScript here
</script>
</body>
</html>
It will work wherever you put it, though.
Also, Sololearn has its own JS section, I recommend you use that
+ 2
var x = prompt("What is your name?");
if (parseInt(x) != NaN) alert("Only use letters!");
couldn't find a better way, this will only return an error if the whole string is just a number
+ 2
<script type ="text/template" id = "player-list-template">
$(document).ready(function(){
$("#text-player").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
});
<input id ="text-player" type="text" placeholder="add a person.." >
<ul id ="player-list">
</ul>
</script>
Add This In body section in html code
+ 1
@ReimarPB @Dondon Bragais
Put it between <script></script> tags or in Javascript secrion in code playground in sololearn
+ 1
@ReimarPB
your answer is very good but he asks about this functionlity in textbox not in a prompt 👍
+ 1
@Maykel Ehab oh oops, I didn't realize that 😅
You can still use line 2 of my example though, if the x variable is the value of the textbox
+ 1
Thank you both for answering my question. I didn't expect a quick response from here. Thank you. Also I dont know how to mention names here so I can't address you both properly hahah Peace
+ 1
You Are Welcome @Dondon Bragais
just write @ followed by the name of the person you want to mention him 👍
+ 1
Okay. Thanks again @Maykel Ehab and @ReimarPB
+ 1
@th3_c0d3r he want the input type to be letters only not numbers
+ 1
@Maykel Ehab
<script type ="text/template" id = "player-list-template">
$(document).ready(function(){
$("#YOURTEXTBOXID").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
});
<input id ="text-player" type="text" placeholder="add a person.." >
<ul id ="player-list">
</ul>
</script>
Where shoul I put the code you gave me. It seems to be not working where I put it XD
+ 1
i think you just forgot to replace #YOURTEXTBOXID by the id of your text box so i edited it for you
0
Oh wow thanks! Should I put it below the closing tag of the </head> or should I put it below the <body>? Sorry I just started learning JavaScript
0
@Maykel sorry, my mistake
0
@th3_c0d3r don't worry 😄
0
@Maykel Ehab
Thank you so much. I'll try it when I get home