Restrict input for some characters through HTML onkeypress - javascript

I am trying to restrict user's input if user is trying to type some characters (like space). To do so I found this post.
But I wanted to make it through HTML's onkeypress attribute. And faced with problem, that if I specify function to return false, then nothing will happen, but if I return false right in HTML's attribute - input won't happen.
I can't understand what am I doing wrong. Can you please tell me how to solve this?
function doMatch() {
return false;
}
$('#test').keypress(function() {
//return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="doMatch();" id="test"/>

But I wanted to make it through HTML's onkeypress attribute.
I recommend you to not do that, since it's better to keep the Javascript behavior out of your HTML code. The name os this technique is Unobstrusive Javascript.
But if you really want to do that, you must use the return keyword to make it work:
<input type="text" onkeypress="return doMatch();" id="test"/>

You just need to add return before doMatch();
function doMatch() {
return false;
}
$('#test').keypress(function() {
//return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="return doMatch();" id="test"/>

Related

How do I get same result using addEventListener (keyup) instead of onkeyup attribute in the HTML?

I want to restrict an input text through a regular expression. In the first example I use the attribute onkeyup = "lettersOnly(this)" inside the HTML, as follows:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username" onkeyup="lettersOnly(this)">
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
</script>
It works but I learnt that this is a bad practice. I found other solution avoiding that, and setting someVariable.onkeyup inside <script> tags. However, my goal is to find another way to get the same result using addEventListener ('keyup', lettersOnly, false). I researched a lot for this specific situation but no answers. Is it possible? I tried the following:
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value.addEventListener('keyup', lettersOnly(input){
input.value = input.value.replace(regex, "");
}, false)
}
</script>
Doesn‘t work. My intention is to avoid the event handler in the html and use instead, the addEventListener. What is wrong in this last coding? Why doesn‘t work? I‘ll really appreciate your patience.
In the code that you said you have tried; the function lettersOnly() will never be called and addEventListener() will never be called.
You can simply change it as follow -
<script>
function lettersOnly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
document.getElementById("username").addEventListener("keyup", lettersOnly(this), false);
</script>
Finally, I found myself a solution and I want to share it.
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
<!--No more “onkeyup” attribute.-->
</form>
<script>
let user = document.getElementById("username");
var regex = /[^a-z]/gi;
user.addEventListener("keyup", ()=>{
user.value = user.value.replace(regex, "");
})
// The “user” variable has been just to simplify a lot of repeated coding, as it is equivalent to “document.getElementById(“username”).
</script>
I don‘t know if this is the best and optimal way to solve my inquire but it works. No “ONkeyup” at all, but using, instead, addEventListener ("keyup", anonymous arrow function). I‘ll really appreciate if anybody has any other suggestion.
The main problem with your second piece of code was that you weren't actually attaching the eventListener to the input element since the outer lettersOnly function was also not called at any time. It appears you resolved this in your own answer, but I'm going to expand upon my comment and suggest using keydown instead.
In the following snippet, I changed the eventListener to attach to keydown instead of keyup. Then we test if the new key (via event.key) matches our regex with .match. If the key pressed is a non-letter character, the match will be non-null, so we want to utilize event.preventDefault() to interrupt the new key from being added to the input value.
Note: this has the added benefit of not needing to use replace or replaceAll to remove the invalid character.
var regex = /[^a-z]/gi;
function lettersOnly(event) {
if (event.key.match(regex) !== null) {
// Since it is an invalid character, we will prevent default
event.preventDefault();
// Log the key to the console for demonstration
console.log(event.key);
// Not needed since we preventDefault()
//event.target.value = event.target.value.replace(regex, "");
}
}
// `username` is equivalent to `document.getElementById("username")
username.addEventListener("keydown", lettersOnly, false);
<form>
<label for="username">Choose a Username:</label>
<input type="text" name="username" id="username">
</form>

Input type="number" selector not working

I want to restrict the input in multiple forms and I'm trying to remove letters from the input on the keyup event. The problem is that It seems to work only on type="text" inputs, but I need it on type="number" inputs.
Fiddle.
NOTE: I need this working at Firefox and IE. On chrome this
functionality isn't neccesary.
$(function(){
$('input[type="number"], [type="text"]').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number">
<input type="text">
You shouldn't have a space between the element selector and the attribute selector.
input [type="number"]
Should be:
input[type="number"]
The [type="text"] happens to work because it matches all elements with a type attribute that is set as text. It really should also be:
input[type="text"]
And the whole selector:
'input[type="number"],input[type="text"]'
There are also issues with the function - the two split('').reverse().join('')? Not needed.
A better approach for this function would be:
$('input[type="number"], input[type="text"]').keyup(function(e) {
this.value = this.value.replace(/[^0-9-]/i, '');
})
Remove Space in between element(input) and attribute([type="text"])
$(document).ready(function(){
$("input[type='text'],input[type='number']").keydown(function(){
$("input[type='text']").css("background-color", "yellow");
});
$("input[type='text'],input[type='number']").keyup(function(){
$("input[type='number']").css("background-color", "pink");
});
});
</script>
The bug was happening because the way IE11 populates the value attribute is strange for type="number".
When I type '1a' then then this.value is '1a', so your code executes correctly.
When I type 'a1' then then this.value is '', so isNaN('') becomes false and your code doesn't execute.
I don't why IE11 is so strange.
I would recommend not using the isNaN and generally improving your coding standards. There were many minor issues already noted in comments.
Here is an example which works in IE11. (This still has some issues testing in Chrome, but you already stated you are not interest in Chrome)
$(function(){
$('[type="number"], [type="text"]').keyup(function() {
this.value = this.value.replace(/\D/g, '');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number">
<input type="text">
You can try this following link,
https://jsfiddle.net/tkfnxpvy/4/
use
$('input[type="number"],input[type="text"]'.keyup(function(e){
});
Okay guys, thanks for all the help, I think I finally solved here.
JSFiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" oninput="this.value = this.value.replace(/[^0-9.,]/g, '');">
<input type="text" oninput="this.value = this.value.replace(/[^0-9.,]/g, '')">

Validate Form Inputs on a good and reliable way

On my page im working on, are a lot of input-forms.
I want to check the user inputs before submit.
Example
HTML/PHP
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
and actually im doing the following in Javascript
Javascript
function dataValidation() {
error=false;
var adress = document.getElementById('adress').value;
var amount = document.getElementById('adress').value;
if (adress == ""){
error=true;
}
if (amount >0 && amount < 999){
}
else {
error=true;
}
if (error == false){
document.forms["myForm"].submit();
}
}
So, basically this works fine for my, but the problem is, i have to create that function for every form, and add a IF for every field
So, im looking for a better solution
Idea 1 : Add a list, wich provides the types of input, like
adress = not empty,
amount = >0 && <999,
and then create a function, which checks all fields with that list
Idea 2: Add a tag or something directly to the input field, what it should contain. and then create a function which checks all the fields
Does somebody have a Idea how this can be done, and would like to help/advise me?
you could try this by jquery as:
your html:
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
<input type="button" id="check_input">
and apply jquery for all input field
$("#check_input").click(function() {
$("input").each(function() {
var element = $(this);
if(element.val() == "") {
element.css("border","1px solid red");
element.attr("placeholder","Field is empty");
return false;
}
});
});
if you have multiple forms with same fields try to call validation externally it will reduce some of your work apart from that i dont know any other method so lets wait for others reply
You might wanna consider using HTML5.
HTML5 can save time writing JS validations. For example to validate an email address you could use the following:
<input type="email" name="email" required />
Notice the type="email" and required. Instead of using js for validating, you could use HTML5 form attributes with Regular Expression Patterns.
For example If I want to create an input field which accepts only one numbers and 3 uppercase letters, I can easily do with it using a RegEx pattern:
<input type="text" pattern="[0-9][A-Z]{3}">
Read a little bit more on HTML5 and RegEx. It could help you.

jQuery click function on an array of inputs

I try to implement a change function on every input field named plz_von.
<input type="text" name="plz_von[]" class="plz_von" placeholder="10000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="20000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="30000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="40000">
I want to do it this way:
$('input[name="plz_von[]"]').change(function() {
alert("got it");
});
I don't know what's going wrong. Any idea? I tried it with the class name as well.
Because [ ] is an attribute selector. You need to escape it.
$('input[name="plz_von\\[\\]"]')
Since you have a class that is common, you might as well use that instead.
$('input.plz_von')
Thanks all for the support. Finally I found the failure.
I had to put the jQuery code into the ready function! This is quite clear, because the function cannot by added to the inputfield, when the input field isn't already loaded in the DOM.. grrr
$(document).ready(function() {
$('input[name="plz_von[]"]').change(function() {
alert("hu");
});
});
Best regards,
Marco

RegExp For Validate Link

I want to validate 7 first alphabet of my input box my code is doesn't work.
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(!this.value.match(/^http\:\/\//) && (txt_url.lenght >= 7 )this.value='http://'+this.value" />
There is a spelling mistake in the function which you have used.(txt_url.lenght).
It should be txt_url.length i believe. Also, if you want to validate a url, there are better regular expressions available on the net.
There are three reasons why that code doesn't work:
lenght should be length.
txt_url.length should be this.value.length.
You're missing a closing ) at the end of the if condition.
Working version:
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(!this.value.match(/^http\:\/\//) && (this.value.length >= 7))this.value='http://'+this.value" />
Demo: http://jsfiddle.net/J5Uxt/
Your code corrected is
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(this.value.match(/^http\:\/\//)==null
&& this.value.length>7)this.value='http://'+this.value;" />
But if you want to automatically put http:// prefix even for shorter domain names like ab.com
then you might use
<input type="text" value="www.example.com" id="txt_url"
onkeyup="if(this.value.match(/^h(t(t(p(\:(\/(\/)?)?)?)?)?)?/)==null)
this.value='http://'+this.value;" />
avoid inline (DOM zero) events and handle this sort of thing centrally
you have a typo in lenght.
are you quite sure you want to do this on key up, rather than, say, on blur, or form submit? It would surely be annoying for the user if you modified the field value every time he or she pressed a key
The below assumes blur, but you can change the event to whatever you want:
jQuery:
$(function() {
$('#text_url').on('blur', function() {
if (!/https?:\/\//.test($(this).val()))
$(this).val('http://'+$(this).val());
});
});
Native JS:
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#text_url').addEventListener('blur', function() {
if (!/https?:\/\//.test(this.value))
this.value = 'http://'+this.value;
}, false);
}, false);

Categories

Resources