I'm trying to write a function, that prevents user, from typing more than one character in the input. Basically, every time user hits any key, the function checks, input value's length, and if it's greater than 1, it sets input value to the first character of typed word. Will this code work out, and if not, how should it look like? (as I mentioned in title, I'm also using jQuery):
function keepOneLetter(){
$("input[type='text']").keypress(function(event){
if($("input[type='text']").val().length > 1){
$(input[type='text']).val() = $(input[type='text']).val($(this).val()[0])
}
}) }
Update
This has been proposed as a duplicate of this one. Well, it could be like that, because:
- When I typed title to search bar (preventing user from typing multiple characters in the input with JS/jQuery), no results popped up, because I mentioned JavaScript and jQuery, while the first question didn't to it at all.
- Speaking of JS/jQuery, if you compare tags, you'll notice, that I used javascript and jquery tags, while the other question had html, forms, input, textbox, so if you were looking for post about, let's say javascript, you wouldn't find original post.
- Eventually, I stuck to HTML solution, as it didn't require JS at all, and it was much faster than writing whole function myself. Well, there was an answer, in which someone wrote function as I initially wanted, and it worked too, but probably due to choosing html solution, Stack Overflow thought, that I've just looked at previously mentioned question, as the best solution considered by author of mentioned above question, was very similar to best solution of my problem.
- Using HTML is optional, it's up to you, whether you stick to pure JavaScript, libraries like jQuery or just HTML. As I said, I used HTML, because it was faster. But I could also use function.