Why is the num pad considered character? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is working fine, but if I use my num pad (right side), it will consider it a character and delete it but the numbers in the left side is accepted. I want my num pad (right side) to be accepted.
<script type="text/javascript">
$("input[name='inputDate']:first").keyup(function(e){
var key=String.fromCharCode(e.keyCode);
if(!( key >= 0 && key <= 9 )) {
$(this).val($(this).val().substr(0,$(this).val().length-1));
}
});
</script>
Updated with this (already solved)
<script type="text/javascript">
$("input[name='birthdate']:first").on('keyup', function(e){
var val = $(this).val();
var key = val.substr(val.length - 1)
var value=$(this).val();
if(value.length === 2|| value.length === 5)$(this).val($(this).val()+'/');
if(!(key>=0&&key<=9))
$(this).val(val.substr(0,val.length-1));
});
</script>

Try this, reading the last character instead of key code:
$("input[name='inputDate']:first").on('keyup', function(e){
var val = $(this).val();
var key = val.substr(val.length - 1)
if(!(key>=0&&key<=9))
$(this).val(val.substr(0,val.length-1));
});
JSFiddle
Note - this won't "protect" you from text being pasted in the input field! For that you'll need to bind input event. Also, a very fast typing can result in some letter "getting trough". So...
A better way of doing the same:
$('input[name="inputDate"]:first').on('input', function(e){
$(this).val( $(this).val().replace(/[^0-9]+/g, '') );
});
JSFiddle
And finally...
If you are creating a date input field and want to make it so that regular visitors can only input a valid date, check out Masked Input Plugin, or maybe some other "input mask" solution.
Be aware that this can still be bypassed with a number of ways and a server-side check is almost always necessary.

Related

How to extract number from backwards in javascript in optimised way [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have to extract a string from backwards upto 10 digits.
Use case is when we select a mobile number it is prefixed with country code sometimes and sometimes we get only the mobile number.
Let's say the number is : +91-84040355236545
I have to extract the number from the end say from 5 to last 10 degits so the end result would be 0355236545
I have a solution of using string.substring method
Here's a simple solution using substrings:
var number = "+91-84040355236545";
var lastTenDigitsNumber = number.substr(number.length - 10);
console.log(lastTenDigitsNumber);
A simpler solution is using slice:
var number = "+91-84040355236545";
console.log(number.slice(-10));
Another solution using a function and RegEX:
function extractTenDigits(number) {
var rx = /(\d{10}$)/g;
var arr = rx.exec(number);
return arr[1];
}
var number = "+91-84040355236545";
console.log(extractTenDigits(number));
I did a simple benchmark and the best solution for small quantity of numbers is the one using slice.
If you provide more details I can provide a more tailored suggestion.
You can try the following using substring :
let str = "+91-84040355236545";
str.substr(str.length - 10 ,10);

Secret Hidden message on keyboard enter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Just had a thought and was wondering if it was possible in the spirit of april fools.
Is it possible to have a secret code that you randomly type in a website similar to that on a gaming console like (a, up, down, b, L1, R1), but on the website, you would type on your keyboard "9 2 k (uparrow) 3" and as long as you're on the website, it does something, let's say alert('hey')? Curious to see how you would do it.
// our combo
var combo = [57, 50, 75, 38, 51];
var keys = new Array(combo.length);
$(document).on('keydown', function(evt){
// remove the earliest of the stored keys
keys.shift();
// push in the latest key pressed
keys.push(evt.which);
// compare with combo array - you could use any comparison method (convert to string,...)
if (!keys.some(function(e, i) { return e !== combo[i] }))
alert('hey')
})
Fiddle - https://jsfiddle.net/kzj5e7Lk/
You'll need to click in the run area (bottom right pane) before you try the key combination.
Well, there's a few things you could do to capitalize on this, and make it more obfuscated so the user has to jump through some more hoops to get the secret key combination, but this should be good enough for a basic implementation.
var code = '.57.50.75.38.51';
var entered = '';
var clearCombo;
//keypress won't register up arrow
$('body').keydown(function (e) {
clearTimeout(clearCombo);
entered += '.' + e.which;
clearCombo = setTimeout(function () {
entered = '';
}, 1000);
if (entered === code) {
alert('i pity the foobar');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That'll require them to enter the code with each character within one second of each other. (set/clearTimeout) It also means they'll have to wait for the timeout to clear out their entered keys if they mess up.
You might also want to check out Mousetrap if you don't mind including an additional library.

How to calculate area of polygon using cartesian coordinates in javascript code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to write javascript code of math equation cross product to calculate area ?
Cross product to calculate area is like this link bellow :
http://mathworld.wolfram.com/PolygonArea.html
Any example?
Try this one and mention if any explanation is needed. I haven't test it, so try for several inputs and be sure it works correctly. ( Of course this can be efficient, but i wrote like that you can easily understand )
<script>
var n = prompt("Please enter the value of n in your equation:");
var arrayOfx=[], arrayOfy = [];
for (var i= 1;i <= n;i++ ){
temp = prompt("Please enter the value of x"+ i +" in your equation:");
arrayOfx.push(temp)
temp = prompt("Please enter the value of y"+ i +" in your equation:");
arrayOfy.push(temp)
}
area = 0;
for (var i=0; i < n-1;i++){
area +=arrayOfx[i]* arrayOfy[i+1] - arrayOfy[i]* arrayOfx[i+1]
}
if (n >2){
area += arrayOfx[n-1]*arrayOfy[0]- arrayOfy[n-1]*arrayOfx[0]
}
alert("The area is "+ area/2);
</script>
The negative area will show negative value. You can add Math.abs(area) if you want positive always.

Highlighting matching nodes in Tree using JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a left tree navigation with a search box on top.When the user enters some text in the Search box,the matching nodes of the tree navigation should get highlighted.
I want to do it using Java script,Can anyone point me to any such examples or documentation for this.
Thanks
Without any html etc can't really see what your setup is! But I assume you want something like the following:
http://jsfiddle.net/cwc66a3d/3/
Use indexOf to find any matching cases among the options, then using the position given, insert a span to contain the matching text with a yellow background to give the impression of highlighting.
The timeout is simply because of delays in event firing, sure to make sure it highlights in real time it is needed.
document.onkeydown = function () {
setTimeout(function () { //delay so can take the event fire into account
var list = document.getElementsByClassName('tree');
for (var i = 0; i < list.length; i++) {
list[i].innerHTML = list[i].innerText;
var pos = (list[i].innerHTML).indexOf(s.value);
if (s.value !== '' && pos != -1) {
var a = list[i].innerHTML.substring(0, pos) + '<span style="background: yellow;">' + list[i].innerHTML.substring(pos,1+ (list[i].innerHTML).indexOf(s.value.substr(s.value.length-1, 1))) + '</span>' + (list[i].innerHTML).substring(1+ (list[i].innerHTML).indexOf(s.value.substr(s.value.length-1, 1)), (list[i].innerHTML).length);
list[i].innerHTML = a;
}
}
}, 50);
};

What is better to use: "2".toString() === 2.toString() OR "2" == 2? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I don't know what is better to use:
var s = "2";
var i = 2;
if(s.toString() === i.toString()){
//do something
}
//OR
if(s == i){
//do something
}
Thanks for the help
You are actually comparing two separate things, in first, you are casting both the variable values to a string and comparing, and the other comparison is lose one i.e you are not actually checking the data types of those variables. so it will return true if you compare string with int with a same value.
According to me, what you should be using is === which will not only compare the values but their data types as well because the ones you are using are both considered lose.
If you do not consider at all about data type then using == will suffice. You don't have to cast the values to a string.
In your first example if for any reason you get a 2 with a space, it will evaluate false (even with ==):
var s = " 2"; // 2 with a sneaky space
var i = 2;
if(s.toString() === i.toString()){ // will be false
//do something
}
Personally I prefer using ===, but I would change the values to integers, instead of to strings.
var s = " 2"; // 2 with a sneaky space again
var i = 2;
if(Number(s) === Number(i)){ // will be true
//do something
}
You don't need the second Number() but, I don't know, you may get data that is also a string.

Categories