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!
Related
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
How can I set html input to accept only numbers and email Id?
<input id="input" type="text" />
As mentioned above in the comments, this should work if you want to accept both 8-digit phone numbers and email addresses:
HTML form code:
<form onsubmit="return validateInput()">
<input type="text" name"mail_or_phone"/>
</form>
JS validation:
function validateInput()
{
var fieldValue= document.getElementById("mail_or_phone").value;
// taken from this SO post: http://stackoverflow.com/questions/7126345/regular-expression-to-require-10-digits-without-considering-spaces
var phoneValidation= /^([\s\(\)\-]*\d[\s\(\)\-]*){8}$/;
var mailValidation= /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (fieldValue.match(phoneValidation)) {
// correct phone structure
return true;
} else if (fieldValue.match(mailValidation)) {
// correct mail format
return true;
} else {
// incorrect structure
return false;
}
}
Here's a fiddle showing an example of the above code. In case of an incorrect answer you should show some kind of warning (not included in the code).
You can set input to type="email" and type="tel".
<input id="input" type="number" />
<input id="input" type="email" />
Check this info out on w3schools
... I see you want the same input, so you would stick with text then check the input using regex
\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}\b.
then whatever regex you need to validate your number
You can run a simple regex against the phone number and the email. That will most likely not catch all issues but it will give you a starting point.
Pseudo code:
//if input is phone
// do something
// else if input is email
// do something else
// else (when it is neither)
// throw an error
or you can even shorten this
// if input is phone or input is email
// do something
//else
//trow error
You can find a ton of regex solutions in the library at regex101.com. There is a whole bunch of email and phone number validators.
One that is supposed to check both (and I didn't look to deeply into the regex) is: \(^\+[0-9]{9,15}$)|(^.+#.+\..+$)\i
This should be true if the input string is a phone or email. However, like I said above, it most likely needs refinement.
I'm trying to wrap my head around RegExp. I currently have a form where I want to validate that the user input is only letters, (although an example of letter and number and spaces would be helpful to). I want this validation to be checked from a submit button. Can anyone help me out with my syntax/logic? Also please explain your answer so I can try to understand it. I'd also like to keep it in just JavaScript if possible, Any help in this matter would be greatly appreciated!
here is my form's code:
First name: <input type="text" name="firstName" /><br />
<span id="firstNameWarnings" style="color:black"> </span>
<button type="submit" onclick="return validateRegistrationForm()" >Register</button>
Note: My JavaScript runs all functions through master function. (submit calls the master function.)
here is my current JavaScript code:
function validateFirstName()
{
var k=document.forms["registration"]["firstName"].value;
var vld=new RegExp([A-Za-z]);
if( k != vld)
{
document.getElementById("firstNameWarnings").style.color = "#F00";
document.getElementById("firstNameWarnings").innerHTML = "First name onyl take letters!";
return false;
}
else
{
document.getElementById("firstNameWarnings").innerHTML = "";
return true;
}
}
Use the test method in RegExp
if( vld.test(vk))
Here's more info on the RegExp test method.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test
You can use this for check - if (/^[a-zA-Z]+$/.test(k)).
^ - matches at the start of the string.
[a-zA-Z] - any character from range.
+ - one or more times.
$ - matches at the end of the string.
wording this question was hard, but here i go. ok, i am using code from this site:
http://www.switchonthecode.com/tutorials/javascript-tutorial-getting-user-input-with-prompt-and-confirm
<script type="text/javascript">
function confirmInput()
{
var ans = confirm("Install a virus and delete all your files?");
alert(ans ? document.getElementById('level').value = "0";
: "If no, do nothing");
}
</script>
<input type="button" onclick="confirmInput()" value="Show me the Question!" />
I have even tried to replace the Text for the answer with the actions, but i get nothing.
How do i add a action to the answer, so when it is yes, i do something, and when no i do not.
I think this is what you are looking for:
function confirmInput()
{
if(confirm("Install a virus and delete all your files?"))
document.getElementById('level').value = "0";
}
there is a syntax error in your code here:
alert(ans ? document.getElementById('level').value = "0"; // this semicolon is invalid
: "If no, do nothing");
It executes till this semicolon and that terminates. Check your console, there should be an error message.
Another thing is that ?: operator can only return a value. It shouldn't contain operations, only values or function, which returns the value.
I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";