Javascript: allow month and year in an input only? - javascript

Basically I'm trying to create a simple input text field that looks like this:
MM/YYYY
I've tried this like so:
<input type="text" value="MM/YYYY" >
But some users seem to go crazy and put strange value in there.
So, I'm trying to force them to keep the format like MM/YYYY using javascrip or jQuery.
Any pointer would be appreciated.
ANSWER:
Here is what I came up with which works exactly like what I want with the help of Jonas's answer:
https://jsfiddle.net/z2a7ydcj/4/

html5 comes with the pattern attribute ;-)
<input type="text" id="foo" pattern="(0[1-9]|1[012])/[0-9]{4}" placeholder="MM/YYYY">
here is some jquery script that tests the input on change and if not valid resets it
jQuery(document).on("change", "#foo", function(){
pattern = new RegExp("/(0[1-9]|1[012])/([0-9]){4}/")
valid = pattern.test(jQuery(this).val())
if(!valid){
jQuery(this).val("")
}
})
you could also manually trigger the form validation by wrapping input into a form and call checkValidity() on it, it will return false and it will highlight all invalid inputs then, so you could check this way before doing any ajaxcalls

You could check each input using js:
<script>
window.addEventListener("load",function(){
document.getElementById("someid").addEventListener("input",function(){
this.value=this.value.split("/").slice(0,2).map((el,i)=>parseInt(el,10)&&i<2?el.slice(0,2+2*i):"").join("/");
});
});
</script>
<input id="someid" />
This just enforces 23/1234. However you might make it more complex:
var length=0;
document.getElementById("someid").addEventListener("input",function(){
if(length>(length=this.value.length)) return; //enable deleting
var mapped=this.value.split("").map(function(char,i){
switch(i){
case 0:
return char=="1" || char=="0"?char:"";
break;
case 1:
return !isNan(parseInt(char,10))?(this[0]=="0"?char:(+char<3?char:"")):"";
break;
case 2:
return "/";
break;
case 3:
case 4:
case 5:
case 6:
return !isNan(parseInt(char,10))?char:"";
break;
default:
return "";
break;
}
},this.value);
if(mapped.length===2) mapped.push("/");
this.value=mapped.join("");
});
It replaces every character with 0 if it does not fullfill special requirenments for the character at that position. It also adds a / after the second char automatically, however this can lead to problems while editing, thats why i recommend to enable the enable deleting above...
http://jsbin.com/razupobamu/edit?output

Related

Javascript Case: "look at" + item

Okay, so this may be a repeat, but I personally haven't seen anything on the internet or in Stackoverflow about this.
I am working on a game project and I have been trying to make a text-based game.
In this game, I have a switch statement, for when the user enters a command.
So far I have things for Inventory and Look (Look around the environment), but how do I work with specific things in a switch statement?
For example:
submit = function(input) {
switch(input) {
case "LOOK":
lookaround();
break;
case "LOOK AT" + item:
look();
}
}
It is the LOOK AT line I am having issues with. I do not know how I can make a string work in that format, unless I had a case for every single item individually, example case "LOOK AT ORANGE" or case "LOOK AT TREE".
I hope I am explaining this thoroughly enough. Can anyone give me some advice?
Thanks
EDIT
I think it is important to note that the user is typing the input into an input box, so the value of the input is going to be a string.
If it will help to see the code I have made, please let me know in the comments below.
EDIT
THANKS FOR YOU HELP GUYS!
I used a regular expression (Thanks #red-devil) and a mixture of slicing. It works perfectly now!
Switch works with constants, not expressions like 'LOOK AT' + anything.
You could define an object for map any of your cases to your own functions. Like that:
var looks = {
'lookat-something' : function() {
alert('something');
},
'lookat-other-thing' : function() {
alert('other thing');
},
};
var x = 'lookat-other-thing';
looks[x]();
It much more flexible than using switch in any way.
If I understood you right, you want the user to be able to input LOOK AT and then any item name. The problem here is that you have this ominous item variable that could stand for anything and this is not going to work.
I would suggest one of these two ways:
Going along the lines of your example:
submit = function (input) {
switch (true) {
case input == "LOOK":
alert("Look")
break;
case input.startsWith("LOOK AT"):
alert(input)
break;
}
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
And secondly, and this is the method I would recommend, you implement a way to parse any input into a command and parameters. A way to do this is to split the input at every space character and then the first value is the command and the rest would be the parameters. This would require you to use a one word command like LookAt and not LOOK AT.
So something like this:
function submit(input) {
var parts = input.split(" ");
var cmd = parts[0];
var args = parts.slice(1);
switch (cmd) {
case "Look":
lookAround();
break;
case "LookAt":
lookAt(args[0]);
break;
}
}

better way to write if else statement

First time writing Javascript. I just would like know if there is a shorter way of writing this:
<p id="demo"></p>
<script>
function myFunction() {
var letter = document.getElementById("myInput").value;
var text;
if (letter === "5544") {
text = "Abar, Marlon 1,800";
} else if (letter === "5545") {
text = "Pia, Darla 1,800";
} else if (letter === "5546") {
text = "Salazar, Alex 1,500";
//etc...
} else {
text = "Incorrect Account Number";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Tried map but I couldn't get it to work.
There isn't really a shorter way to write an if statement in that way (which I will assume is what you're asking). However, there could be a few different ways to write this depending on how many things you want to check.
Use a Switch statement
There is a cleaner way when dealing with multiple cases that letter could be.
This would be a switch statement and it would look like this:
var text;
switch (letter) {
case "5544":
text = "Abar, Marlon 1,800";
break;
case "5545":
text = "Pia, Darla 1,800";
break;
// more cases
default:
text = "Incorrect Account Number";
break;
}
This reads a little better than an if else statement in some cases. The default keyword here acts as your else clause in an if else statement. The case acts as your different if statements if you will.
Essentially, the switch statement above will fall through each of the cases it defines until it finds a case that matches letter (such as "5544"). If none matches, it hits the default case. The break keyword at the end of each case stops things from falling through to the next defined case once a match is found.
This method could get cumbersome with more than 6 or 7 cases.
Create an object and look up the value
Now, a shorter way to get the value you want could be to define an object and get the value based on what has been entered like so:
var letter = document.getElementById('selector').value;
var obj = {
'5544': 'Abar, Marlon 1,800'
};
if (letter in obj) {
// do something if found
}
else {
// do something if not found
}
This could be an easy way to get a value if you have many values to check.
Other thoughts
As a side note to all of this, there are short hand if statements called ternary statements which you can find here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator ... However, I would not recommend nesting these as it becomes very complicated and not very readable.
Conclusion
So, to reiterate the answer to your question: No, there isn't really a shorter way to write an if else statement with many values. You can use a switch statement to make it cleaner. Use the object lookup method if you have many values you would like to check.
JavaScript has object (map) literals. Use them for terse code. In your final application you'll get the data for the map from someplace else and not code it directly into your website, but if you did, it would look like this:
document.getElementById( "demo" ).innerHTML = {
"5544" : "Abar, Marlon 1,800",
"5445" : "Pia, Darla 1,800",
...
}[ document.getElementById( "myInput" ).value ];
you can use switch for a long if - else -if ladder:
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
1)The switch expression is evaluated once.
2)The value of the expression is compared with the values of each case.
3)If there is a match, the associated block of code is executed.
if you need basic tutorials in java script then you should try w3 schools.

How when entered a number is entered the date is displayed?

javascript, when a number is entered eg. 1 being Monday the message received is "It's Monday".
I am using a switch statement for this.
The code I am using is:
function DayOfTheWeek
{
var day='1';
switch (day)
{
case '1';
alert ("It\'s Monday");
break;
case '2';
alert ("Its\s Tuesday");
break;
case '3';
alert (It\'s Wednesday");
break;
default:
alert("Not a valid day");
break;
}
Below is the input form code:
<form name="form3" method="GET" action= "parse.php">
<input type="number" name="textEntry3" />
<input type="button" value="Click me 3" onclick="DayOfTheWeek(textEntry3.value);"\>
</form>
I cannot seem to get this working at all
Has anyone got any ideas?
Thanks
Welcome!
I would encourage you to show your effort in resolving the matter for yourself first. However, as you are new, try the following.
The function you have defined takes no argument. You are statically assigning 1 to your variable. Define a parameter for your function and use it in the switch statement. See W3C School for a tutorial on Javascript functions.
You might also want to read the site's guidelines on how to ask questions!

Can you automatically associate Javascript to a DOM element based on its CSS class?

So right now I have an input validation method structured something like this:
function validate(element, regex);
'element' is the input DOM element and 'regex' is the regular expression that the method checks the user's input against. If the input doesn't matchup with regex, the input element outline changes to red. If the user input is valid, then the outline changes back to black.
Is there a way to associate this function with a CSS class so that every element with that class will automatically call that function?
<input type="text" id="text_field" class="yearvalidate"/>
So class "yearvalidate" would send a regular expression to validate() that limits the input to 4 digits. And this would be done automatically instead of explicitly writing Javascript to call validate for the textfield.
Is there a way to do this or do I have to make an explicit call in Javascript?
With jQuery:
$('input').each(function(i,e) {
var regex = getRegex($(e).attr('class'));
if (regex) validate(e, regex);
});
You'll have to create another function getRegex() for turning 'yearvalidate' into /\d{4}/ though.
function getRegex(classname) {
switch(classname) {
case 'numbervalidate':
return /\d+/;
break;
case 'yearvalidate':
return /\d{4}/;
break;
}
}
You could do something like -
$('.yearvalidate').change(function() {
//check value using your regex
});
That will hook up a function that fires every time an element with the class 'yearvalidate' loses focus.
You need some sort of framework to do the wiring for you. My suggestion would be to use jQuery to bind changes for any element with class "yearvalidate" to your validate function.
$(function() {
$('.yearvalidate').change(validate);
});

Writing a custom text box for web pages

I want to capture user's activities on my textbox. Since a normal textbox won't give me enough information on what my user is doing currently with it, I want to start on a custom HTML text box.
For e.g.
If my user is typing
Hello world! (Say he made a typo...) I should be able to tell him that,
H e l l o w o r l e [bksp] d !
also if a user selects a text, I should be notified about it.
P.S. I've mentioned a custom text box inorder to be generic. If I can make use of / create something like a plugin on the already available text box or say even a javascript, it's fine.
Your best bet would be to add functionality to the existing <input type="text"> using javascript.
I don't know how you would create your own textbox as browsers just interpret html which only contain the predefined elements in the HTML specification (apart from certain exceptions such as ActiveX).
As a solution regarding to what you want you can capture every keypress using the onKeyUp event of your document. You can catch every keypress and display them to your liking.
small example:
<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck()
{
var keyID = event.keyCode;
var keypressed;
switch(keyID)
{
case 16:
keypressed = "Shift";
break;
case 17:
keypressed = "Ctrl";
break;
case 18:
keypressed = "Alt";
break;
case 19:
keypressed = "Pause";
break;
case 37:
keypressed = "Arrow Left";
break;
case 38:
keypressed = "Arrow Up";
break;
case 39:
keypressed = "Arrow Right";
break;
case 40:
keypressed = "Arrow Down";
break;
}
document.write(keypressed);
}
</script>
for a list of all the keycodes see here.
[Update]
I just saw that you are also want to know when someone selects text and luckily for you there are also events that handle this:
An <INPUT TYPE = "text"> aswell as a <TEXTAREA> have an .onSelect event which you can capture. Then you can get the selected text using the method you find on this other StackOverflow Question: How to get selected text from textbox control with javascript
If you are working heavily in javascript I suggest you take a look at JQuery (if you haven't already). It will definitely make your life easier.

Categories