Validate latitude using javascript - javascript

How can I restrict an input field for enter latitude using javascript?
The following is the piece nof code which i have tried.
$('#latitude').on( "keypress",function (e) {
var keypress = e.keyCode || e.which || e.charCode;
var key = String.fromCharCode(keypress);
var regEx = /^[-|+]?[0-9]{0,2}(.[0-9]{0,6})?$/;
var txt = $(this).val() + key;
if (!regEx.test(txt)) {
if(keypress != 8){
e.preventDefault();
}else{
}
}else{
}
});
Here i found the issue that i can enter a special character at the first position. Please help me...

In your validation also include the following line:
if (!regEx.test(txt) && !isNaN(txt)) { .... }

try this, also note that N and S can also be included in latitude
"^(?:90|[0-8][0-9]):[0-5][0-9]:[0-5][0-9][NS]$"

This question has already been answered here Regular expression for matching latitude/longitude coordinates?.
It suggests the following regular expression:
^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$

Related

More than one comma restrict using javascript

In my textbox I allowed only integer value and comma it will control using javascript.Now my doubt how to control more than comma continuously (i.e)1,2,3,4 is to ok then 1,2,3,,4,,5 its need restricted.Its possible in javascript.
<p:inputText onKeyPress="onlyAllowDigitComma(event);"/>
Your answer doesn't show how far you go with your solution. I suppose code bellow is what you wanted, also I suppose you need removing comas from start and end.
<input type="text" onkeypress="onlyAllowDigitComma(event,this);" onkeyup="onlyAllowDigitComma(event,this);"/>
<script>
function onlyAllowDigitComma(e,l){
var k = e.which;
if ((k <= 47 || k >= 58 ) && k!=44 && k!=8 && k!=0) {
e.preventDefault()
};
l.value=l.value.replace(/,,/g,',');
}
</script>
Use a regex to validate your input. If the first match you get is the same as the whole input, then you're good to go.
The regex you're looking for is /(\d,?)*/g (Test Link)
For the sake of simplicity, I did the following code with the 'keyup' event to avoid shortcuts problems. You may also want to check on copy / paste event.
let myInput = document.getElementById('myInput');
let myInputValue = myInput.value;
myInput.addEventListener('keyup', function(event){
if(isPerfectMatch(myInput.value, /(\d,?)*/g)){
console.log('Format is correct.');
myInputValue = myInput.value;
}
else {
console.log('Wrong format');
myInput.value = myInputValue;
}
});
function isPerfectMatch(value, regex){
let match = value.match(regex);
return match !== null && match[0] == value;
}
(Demo JSFiddle)

How to determine if user is beginning new word in JS?

How would you, with JS or jQuery, determine if what the user is typing is a new word?
What I want to do:
I am writing a documentation tool with autocompletion for different types. If you type f.e. # it will populate Java Classes in a box, # would populate test classes, etc. Now I don't want to populate these values, if the user is writing something like an email like yourname#domain.com. So I need the values to populate only when it's the beginning of the word.
I am aware of keydown, keyup events, etc. I just don't know how to check for this certain kind of event properly.
One way would be to save every typed letter in a variable and then check if the previous "letter" was a space and if it was, we know it's a new word. Is this the best/most efficient way to do this?
One way is to check what's before the # in the input box, using selectionStart:
onload = function() {
var io = document.getElementById("io");
io.onkeypress = function(e) {
if(e.charCode == 64 && (
io.selectionStart == 0 || io.value[io.selectionStart-1].match(/\s/)))
document.getElementById("ac").innerHTML = "autocomplete!";
else
document.getElementById("ac").innerHTML = "";
}
}
<input id="io">
<div id="ac"></div>
Try this JSFiddle. I'm performing the check like so:
var text = $("#test").val();
if (text.length == 0 || text.charAt(text.length - 1).match(/[\s\b]/)) {
$("#result").html("new word");
} else {
$("#result").html("no new word");
}
You can easily adapt the .match() pattern if you like to include other characters as "whitespaces" (e.g. curly braces) for your Editor.
Assuming text is entered in a text input with id="txtchangedetection":
$("#txtchangedetection").change(function(){
console.log("The text has been changed.");
});
/*This is `JQuery`*/
I've understood you want to detect word changes in the input. Please precise if I'm wrong. What do you mean by 'new word' ?
One solution will be like this :
1- declare a variable "newWord = true"
2- with keydown event check if the key pressed is a space
if YES : newWord = true
if NO : newWord = false
var newWord=true;
$("#textarea").keydown(function(e){
if(e.keyCode == 32){
newWord=true;
}else{
newWord=false;
switch(e.keyCode){
//work to do
}
}
})
use keypress on your input field... populate the array inside the if with your special chars
if(prev == 13 || prev == 32 || $('#doc').val().length==0 || prev==null){
listen = true;
}else{
listen = false;
}
prev = e.which;
if(listen && $.inArray(String.fromCharCode(e.which),["#","#"]) != -1){
e.preventDefault();
alert("populate box here");
listen = false;
prev = null;
}
the fiddle https://jsfiddle.net/6okfqub4/

Javascript Regex to limit Text Field to only Numbers (Must allow non-printable keys)

I have received PHP/JS code from previous developer and I need to add number validation to a Mobile Number field. I already have the HTML validation in place but I need to add that if someone presses an invalid key, that it doesn't get displayed only to highlight the field later in red because it contains invalid input.
I've seen many regex's used and tried them but they had an either/or effect from what I need which is: If a letter or special character is entered, do not accept and do not display, all other input (digits, keys) is accepted (I need the invalid character not be displayed at all, not displayed and then erased). The regex that is working the most now is this:
function filterNonDigits(evt)
{
var event = evt || window.event;
var keyentered = event.keyCode || event.which;
keyentered = String.fromCharCode(keyentered);
//var regex1 = /[0-9]|\./;
var regex2 = /^[a-zA-Z.,;:|\\\/~!##$%^&*_-{}\[\]()`"'<>?\s]+$/;
if( regex2.test(keyentered) ) {
event.returnValue = false;
if(event.preventDefault) event.preventDefault();
}
When I used the commented regex1 (with the IF condition reversed), naturally it limited input to only digits thus preventing all keys such as Delete, BackSpace, etc. When using regex2, I still can't press Delete or the digits from the numpad.
So my question is, can the above code be modified to accept only digits but also allow keys? Another important point is that I need a method that doesn't use keycodes (8, 24 etc) for those key, in order to make sure all keyboard types can be used.
New Update:
So my solution is as follows: If the "oninput" property exists, I use the solution provided by Ehtesham and if it doesn't, the backup uses the solution provided by Rohan Kumar. So it's something like this:
if (obj.hasOwnProperty('oninput') || ('oninput' in obj))
{
$('#mobileno').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
}
else
{
$('#mobileno').on('keypress',function(e){
var deleteCode = 8; var backspaceCode = 46;
var key = e.which;
if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 && key<=40) || key===0)
{
character = String.fromCharCode(key);
if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' )
{
return true;
}
else { return false; }
}
else { return false; }
});
}
Thanks.
The best method here is to use input event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.
$('.numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
See it here
You can check if input event is supported by checking if the input has this property if not you can use onkeyup for older browsers.
if (inputElement.hasOwnProperty('oninput')) {
// bind input
} else {
// bind onkeyup
}
A nice solution is described in a previous post:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Try it like,
CSS
.error{border:1px solid #F00;}
SCRIPT
$('#key').on('keydown',function(e){
var deleteKeyCode = 8;
var backspaceKeyCode = 46;
if ((e.which>=48 && e.which<=57) ||
(e.which>=96 && e.which<=105) || // for num pad numeric keys
e.which === deleteKeyCode || // for delete key,
e.which === backspaceKeyCode) // for backspace
// you can add code for left,right arrow keys
{
$(this).removeClass('error');
return true;
}
else
{
$(this).addClass('error');
return false;
}
});
Fiddle: http://jsfiddle.net/PueS2/
Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?
This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.
function filterNonDigits(evt)
{
var event = evt || window.event;
var val = event.target.value;
var filtered = val.replace(/[^0-9]/g, '');
if(filtered !== val) {
event.target.value = filtered;
event.target.className += " error";
}
}
http://jsfiddle.net/mEvSV/1/
(jquery used solely to easily bind the keyup function, you won't need it for your actual script)
/\d/ is equivalent to the above described /[0-9]/. src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-digit
This is a bit more concise...
this.value = this.value.replace(/\D/gm, '');

Show image when key is pressed with jQuery

im trying to make a simple app that when a key is pressed on the users keyboard an image appears respective to that letter. I would like to do this for the entire alphabet (a, b, c...)
if a is pressed a.jpg shows up on my page, if r was pressed r.jpg would appear and so on.
I was going to do this with a mega list of if else statements only im sure there must be another way?
var ctrlPressed = false;
$(window).keydown(function(evt) {
if (evt.which == 17) { // ctrl
ctrlPressed = true;
alert('sdf');
}
})
This is how I would go about doing this:
var letters = "abcdefghijklmnopqrstuvwxyz";
letters = letters.split("");
//I'm lazy; you should define an array of letters
$(window).keydown(function(e){
key = e.which - 65; //makes a-z = 1-27
key = letters[key];
$('img[src="' + key + '.jpg"]').show();
}
Here is a working jsFiddle
Source(s)
jQuery API - keydown
jQuery API - Attribute Equals Selector
MDN - String.split
How about an array of image references where the index maps to the evt.which value
var images=[];
images[64]='a.jpg';
images[65]='b.jpg';
images[66]='c.jpg';
//...etc...
$(window).keydown(function(evt) {
var image=images[evt.which]'
if(image){
alert(image);
}
})
A bit ugly, probably not the most efficient, but easy to follow :)
Seems that event.which for letters corresponds to the ASCII value. So, you could do something like the following:
$(window).keydown(function(evt) {
if (evt.which >= 65 && evt.which <= 90){
$('img[src="' + String.fromCharCode(evt.which).toLowerCase() + '.jpg"]').show();
}
});
You should named your image files with the alphabet KeyCodes.
For instance the entered letter "a" must be named "97.jpg".
So you can call it from your jquery like this:
$(document).ready(function(){
$("#input").bind('keypress', function (e) {
console.log(e.which); //or alert(e.which);
$("#Image").attr("src", e.which + ".jpg");
});
});
I would get the key value and then just match it again a-z. Try something like:
$(window).keydown(function(e) {
var key = String.fromCharCode(e.which).toLowerCase();
if(/[a-z]/i.test(key)) {
alert(key+'.jpg');
}
});
Demo: http://jsfiddle.net/BMZaF/

Determine if key pressed is in provided array

I have code similar to this:
$("#some-input").keyup(function (event) {
var availableKeys = [".", ",", ";"];
var key = String.fromCharCode(event.which);
if (availableKeys.indexOf(key) != -1) {
alert("Derp");
}
});
However it does not work as I expected. The event.which/fromCharCode combination works like this properly on digits or letters (capital ones) and this is the correct behaviour since (I presume) event keycodes are different than charset entries.
Is there a workaround other than directly specifying keycodes for comparison (keeping the array of characters is a priority)?
Try changing your array to contain the keycodes of the keys you wish to check for:
$("#some-input").keyup(function(event) {
var availableKeys = [190, 188, 59]; // ".", ",", ";"
if (availableKeys.indexOf(event.which) != -1) {
alert("Derp");
}
});
Example fiddle here
Here's a full list of keycodes
Edit
After a little investigation it appears your method should work, but the implementation of String.fromCharCode is flawed - at least for the symbol keys. While pressing . returns the correct keyCode of 190, when you run that through fromCharCode you get the string ¾. Other keys such as [ and # show similar behaviour. I assume this is due to internationalisation, maybe someone else could confirm.
You could use keypress instead. Like
$("#some-input").bind('keypress', function(e) {
var availableKeys = [".", ",", ";"];
if(availableKeys.indexOf( String.fromCharCode( e.which ) ) > -1 ) {
alert('Derp');
}
});
Looks to me as though you should try using charCodeAt to convert your keys to keycodes at comparison time. eg:
alert (".".charCodeAt(0)); // alerts 46
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/charCodeAt
This very likely is an issue related to the way you are getting the key/char code. Try getting the char/key code like:
var code = (event.charCode != 0) ? event.charCode : (event.keyCode != 0 ? event.keyCode : event.which);
var key = String.fromCharCode(code);
Can't find any issues in any other part of your code.
This is not working because you are using ' as one of the key and also as char separator in the array so its confusing the program otherwise its working for . and ;.
["." , " , " , ";"] . It consider 4 different elements.
use belwo code:
$("#some-input").keypress(function (event) {
var availableKeys = ",.;";
var key = String.fromCharCode(event.which);
if (availableKeys.indexOf(key) != -1) {
alert("Derp");
}
});
fiddle : http://jsfiddle.net/AVcrw/1/
You could use underscore.js:
$("#some-input").bind('keypress', function(event) {
var aKeys = [13, 32];
if ( _.contains(aKeys, event.which) ) {
console.log("char :" + event.which);
}
});

Categories

Resources