Currently I am trying to setup my contact form to give an error message when an invalid email is entered. When a blank or incorrect e-mail is submitted the page should do the following:
Sign Up text changes to 'Retry'
Red text appears within input field stating 'Address entered not valid'
When the user focuses on the input field, or presses 'retry'; all the form elements should go back to their original state. I have been able to get the text to change from red to black using the onFocus method. I attempted to create a small little javascript named reset, which I hoped to change the DIV text from 'Retry' back to 'Sign Up'.
I'm certain my issue is with the Javascript. Can someone point me in the right direction? :)
For code reference:
http://itsmontoya.com/work/playdeadcult/indextest.php
One way of doing this is, with the html:
<form action="" method="post">
<fieldset>
<label for="emailAddress">Sign up for the newsletter</label>
<input type="text" id="emailAddress" name="email" />
<button id="submitButton" type="submit">Submit</button>
</fieldset>
</form>
And the JavaScript:
var emailEntry = document.getElementById('emailAddress');
var button = document.getElementById('submitButton');
var defaultButtonText = button.innerHTML;
emailEntry.onblur = function(){
var val = this.value;
// the following IS NOT a valid test of email address validity
// it's for demo purposes ONLY
if (val.length < 5 && val.indexOf('#') == -1){
button.innerHTML = 'retry';
button.style.color = 'red';
}
else {
button.innerHTML = defaultButtonText;
button.style.color = 'black';
}
};
button.onclick = function(){
// prevent submission of the form if the email was found invalid
// and the innerHTML was therefore set to 'retry'
if (this.innerHTML == 'retry'){
return false;
}
};
JS Fiddle demo.
Try this instead:
function validate() {
if($("#buttonDiv").html()== 'Retry')
{
// oops! They are trying to get back to where they were by
// re-clicking retry. Let's reset this thing
reset()
return false;
}
var emDiv = document.getElementById('email') // only look up once.
if(emDiv) {
// the space after the . should allow for 6 long
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,6})$/;
var address = emDiv.value;
// good form issue -- never use == false. use !
if(!reg.test(address)) {
emDiv.value = 'Address entered not valid';
emDiv.style.color = '#bf4343';
emDiv.style.fontSize = '12px';
$("#buttonDiv").html( 'Retry' );
return false;
}
}
}
Is it just the commented out block of your reset() function what you need help with? If so, you can try the jQuery version of it since you have jQuery loaded anyway =)
The following is for your reset() function which changes text color to red:
$('#email').val('').css('color', '#FF0000').css('font-size', '18px');
The following is for your blur() function which changes text color to black. Attach this to your email input text box as well and you should be set:
$('#email').blur().css('color', '#000000');
Related
I want to allow users to see what they type in a password field. For instance, as soon as they type a letter in the field, they should see what was typed and the letter should change back to its default bullet.
This jQuery plugin does what you want: https://code.google.com/archive/p/dpassword/
The blog post contains the details.
Another option is to swap the type of the field using a checkbox ("Show password?"). Switching the type of the input element between text and password should achieve this. If that doesn't work, you need to create a new input element and copy the value.
Note on security: The password is hidden for a reason. Just to give you an idea of the possible attacks, here is the ones I know of:
If a smart phone is lying on the table next to your keyboard, then the vibrations caused by typing can be recorded and the keys you pressed can be calculated from that.
If the monitor is visible from outside the building, a good telescope can read you screen over quite a distance. If you wear glasses or there is a teapot, you can still read that at 30m.
So be aware that displaying a password does compromise security.
Related articles:
I Spy Your PC: Researchers Find New Ways to Steal Data
http://css-tricks.com/better-password-inputs-iphone-style/
Building uppon #SubhamBaranwal's answer that has the major drawback of losing the password field's value, you could do something like the following:
$(_e => {
const frm = $('#my-form');
const passField = frm.find('.pass');
const passCopy = $('<input type="hidden" />');
passCopy.prop('name', passField.prop('name'));
passField.prop('name', null);
passField.prop('type', 'text');
frm.append(passCopy);
let timer;
passField.on("keyup", function(e) {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
timer = setTimeout(function() {
copyPass();
passField.val(createBullets(passField.val().length));
}, 200);
});
function createBullets(n) {
let bullets = "";
for (let i = 0; i < n; i++) {
bullets += "•";
}
return bullets;
}
function copyPass() {
const oPass = passCopy.val();
const nPass = passField.val();
if (nPass.length < oPass.length) {
passCopy.val(oPass.substr(0, nPass.length));
} else if (nPass.length > oPass.length) {
passCopy.val(oPass + nPass.substr(oPass.length));
}
}
/* for testing */
frm.append('<input type="submit" value="Check value" />');
frm.on('submit', e => {
e.preventDefault();
copyPass();
alert(passCopy.val() || "No Value !");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<input class="pass" type="password" name="pass" />
</form>
However, this remains a simplistic implementation that will only support editing the password from the end (appending characters or backspaces). For a full implementation, you'd have to check and record where the current selection lies at each keyUp, and then modify the recorded value according to what you get after the input field was updated. Far more complicated
I think you want something like this JSFiddle
HTML Code -
<input class="pass" type="password" name="pass" />
JS Code -
function createBullets(n) {
var bullets = "";
for (var i = 0; i < n; i++) {
bullets += "•";
}
return bullets;
}
$(document).ready(function() {
var timer = "";
$(".pass").attr("type", "text").removeAttr("name");
$("body").on("keyup", ".pass", function(e) {
clearTimeout(timer);
timer = setTimeout(function() {
$(".pass").val(createBullets($(".pass").val().length));
}, 200);
});
});
I have been trying form validation in javascript and html. I am stuck with the use of onblur(). The idea is that the user enters his name. If he moves out of the input area (textbox) without entering anything, then error message should be shown.
But according to my code below even if I enter anything, it still shows alert no name entered.
<form>
<input type="text" id="fn" value="First Name" onfocus="fnm()" onblur="chfnm()"/>
</form>
function fnm()
{
document.getElementById("fn").value=""; //clears default value of textbox
}
function chfnm()
{
var f=document.getElementById("fn");
for(var i=0;i<f.length;i++)
{
if(i!=(f.length-1))
fname= fname +f.elements[i].value +"<br>";
else
fname= fname+ f.elements[i].value;
}
if(fname=="") //error is fname is always an empty string
{
alert("Please fill your first name");
document.getElementById("fn").focus();
}
}
I am new to javascript so any new ideas are appreciated and welcome.
If you want to do validate that user inputting the name or not, you can simply use this code. If so you are putting extra code with for loop.
function fnm(){
document.getElementById("fn").value=""; //clears default value of textbox
}
var fname = "";
function chfnm(){
fname = document.getElementById("fn").value;
if(fname==""){
alert("Please fill your first name");
document.getElementById("fn").focus();
}else{
alert("your name " + fname);
}
}
DEMO
Just add required tag of html5 so no need to add extra java script function for checking
I am creating a contact form. I want to use ghost text in my input forms, but with the ghost text Javascript added to my code work, my form requirement alerts do not work anymore.
I believe it is because the code is reading the ghost text as the form being filled in, and not empty. I need the alerts to show up when people have filled nothing in.
I think I need to make it so the ghost text has no value, but I don't understand how to achieve this.
Here an example of one of my input fields with a form requirement:
<label for='name' >Your Name *: </label
<input type='text' name='name' id='name' value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='contactus_name_errorloc' class='error'></span>
Here is the ghost text JS:
<script>// Reference our element
var txtContent = document.getElementById("name");
// Set our default text
var defaultText = "Full Name*";
// Set default state of input
txtContent.value = defaultText;
txtContent.style.color = "#CCC";
// Apply onfocus logic
txtContent.onfocus = function() {
// If the current value is our default value
if (this.value == defaultText) {
// clear it and set the text color to black
this.value = "";
this.style.color = "#000";
}
}
// Apply onblur logic
txtContent.onblur = function() {
// If the current value is empty
if (this.value == "") {
// set it to our default value and lighten the color
this.value = defaultText;
this.style.color = "#CCC";
}
}</script>
Here is my form alert JS:
var frmvalidator = new Validator("contactus");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your full name.");
And here is the form alert PHP:
//name validations
if(empty($_POST['name']))
{
$this->add_error("Please provide your full name.");
$ret = false;
}
i did a little bit of looking around and found this this is what i think you are looking for :)
So basically what I want is for the submit button to be disabled until a certain word count has been reached in the text area.
I have had a look around and tried to find ways to do it, with no luck.
Any tips or help?
<form method="post" id="writearticle" action="submitarticle.php">
<script>
$('#writearticle').submit(function(event) {
var text = $("#content").val();
text = text.split(" ");
// check for at least 10 words
if(text.length < 10){
console.log("prevented");
// prevent submit
event.preventDefault();
return false;
}
console.log("submitted");
});
</script>
<textarea rows="30" cols="85" id="content" name="content" placeholder="Write the article here. Try to abide by the instructions and keywords provided."></textarea>
<br />
<input type="submit" name="submitarticle" value="Submit Article" class="submit" />
<br /><br /><br /><br /><br />
</form>
Show us your code.
1) Set onclick event for the submit button
2) Check length in textarea
3) return false and preventDefault() if there is not enough words.
You can check the word/charactor count in keyup event.
see this example at http://elylucas.net/post/Enabling-a-submit-button-when-a-textbox-has-value-in-jQuery.aspx
instead of checking for a value, you split the input string in the text box and see the length of the array is more than your desired word count
Use the textchange (not built-in) event to accurately detect text changes via keyboard, paste etc. - http://www.zurb.com/playground/jquery-text-change-custom-event
$('textarea').bind('textchange', function () {
// $(this).val() contains the new text
});
In your text-change event, check the length/count the words in your text and enable disable the submit button as needed (make sure its initially disabled).
You catch the submit event, you count the words in the textarea and only submit if it is high enough. Example:
$('#targetForm').submit(function(event) {
var text = $("#myTextarea").val();
text = text.split(" ");
// check for at least 10 words
if(text.length < 10){
// prevent submit
event.preventDefault();
return false;
}
});
DEMO
Try out below lines of code,
$(document).ready(function() {
$(".submit-name").attr("disabled", "true");
var minLength = 100;
$("#your-text-area").bind('keyup', function(event) {
var String = $("#your-text-area").val()
if (String.length >= minLength ) {
$(".submit-name").removeAttr("disabled");
} else {
$(".submit-name").attr("disabled", "true");
}
});
});
I don't do much with Javascript.
What I'm looking to do is have a form where users can enter their zip code to see if they are within a select number of zip codes (the client's service area).
If their zip code is in the list, I want to send them to a URL for scheduling an appointment. If it isn't in the list, I want some sort of alert that says "Sorry, your zip code isn't in our service area".
I've got something adapted that kind of works, but sends the user to the page regardless of what they enter.
Any help is greatly appreciated!
<form name = "myform" action="http://www.google.com/">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5" onchange = "checkZip()">
<button id="submit">Submit</button>
</form>
<script type = "text/javascript">
function checkZip() {
var z = document.myform.zip;
var zv = z.value;
if (!/^\d{5}$/.test(zv)) {
alert("Please enter a valid Zip Code");
document.myform.zip.value = "";
myfield = z; // note myfield must be a global variable
setTimeout('myfield.focus(); myfield.select();', 10); // to fix bug in
// Firefox
return false;
}
var codes = [ 12345, 12346, 12347, 12348, 12349, 12350 ]; // add as many
// zip codes as
// you like,
// separated by
// commas (no
// comma at the
// end)
var found = false;
for ( var i = 0; i < codes.length; i++) {
if (zv == codes[i]) {
found = true;
break;
}
}
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
document.myform.zip.value = "";
return false;
} else {
alert("Press okay to go forward to schedule an appointment");
}
}
</script>
Non-submit Button (simple) Solution
<form name = "myform" action="http://www.google.com/">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
<button type="button" onclick="checkZip();" id="submit">Submit</button>
</form>
Note: a button with type="button" is a push button and does not submit w3c
And change the last block of checkZip() to:
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
document.myform.zip.value = "";
//do nothing
} else {
alert("Press okay to go forward to schedule an appointment");
document.myform.submit();
}
The changes I made were the following:
Move the onclick attribute from the input element to the submit button
Change the submit button to have a type of 'button', which makes it a push button. Push buttons do not automatically submit the the current form.
Note: This will not stop the situation where pressing enter inside the input element submits the form. You will need an onSubmit="" handler according to the next solution to handle that use case.
Submit button (simple) solution
<form name = "myform" action="http://www.google.com/" onsubmit="checkZip()">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
<button onclick="checkZip();" id="submit">Submit</button>
</form>
Note: a button with no type is a submit button by default w3c
And change the last block of checkZip() to:
if (!found) {
alert("Sorry, the Zip Code " + zv + " is not covered by our business");
return false;
} else {
alert("Press okay to go forward to schedule an appointment");
return true;
}
The changes I made were the following:
Move the checkZip() call to the onsubmit attribute on the form
Change checkZip() to return true/false
On Change Solution
This solution most closely replicates yours. However it adds more complexity:
The Form:
<form name = "myform" action="http://www.google.com/" onsubmit="onFormSubmit();">
Enter Your Zip Code
<input type = "text" id="zipCode" name = "zip" size = "5" maxlength = "5" onchange = "onZipChange()">
<button id="submit">Submit</button>
<div id="invalidZipMsg" style="display:none;">
Sorry, but we do not service your area.
</div>
</form>
The JavaScript:
/**
* Returns true if we receive a valid zip code.
* False otherwise.
*
* #param zipCode The zip code to check
* #returns True/fase if valid/invalid
*/
function isValidZip(zipCode){
var validZipCodes = {'12345':true,
'12346':true,
'12347':true,
'12348':true,
'12349':true,
'12350':true
};
//can do other checks here if you wish
if(zipCode in validZipCodes){
return true;
} else {
return false;
};
}
/**
* Run on invalid zip code.
* Disables form submission button and shows
* error message.
*/
function invalidZipCode(){
var invalidZipMsg = document.getElementById('invalidZipMsg');
invalidZipMsg.style.display = "block";
var submitButton = document.getElementById('submit');
submitButton.disabled = 'true';
}
/**
* Run on valid zip code. Enables form
* submission button and hides the error message.
* #returns
*/
function validZipCode(){
var invalidZipMsg = document.getElementById('invalidZipMsg');
invalidZipMsg.style.display = "none";
var submitButton = document.getElementById('submit');
submitButton.disabled = 'true';
}
/**
* onChange handlers for the zip code input element.
* Will validate the input value and then disable/enable
* the submit button as well as show an error message.
* #returns
*/
function onZipChange(){
var zipCode = document.getElementById('zipCode');
if(isValidZipCode(zipCode.value)){
validZipCode();
} else{
invalidZipCode();
};
}
/**
* Run on form submission. Further behavior is the same
* as #see onZipChange. Will stop form submission on invalid
* zip code.
*/
function onFormSubmit(){
var zipCode = document.getElementById('zipCode');
if(isValidZipCode(zipCode.value)){
validZipCode();
return true;
} else{
invalidZipCode();
return false;
};
}
Notes
There are many ways to solve this problem. I just chose the two easiest ones and one that I feel offers a better user experience. The non-submit solution is a good example for when you have buttons that don't submit, but provide other actions that don't require a form submission. The last one has the best user experience in my opinion, but that is just an opinion.
Off Topic
If you have time I would suggest you check out many of the fine JavaScript libraries that are available. They help introduce complex/advanced issues with simple solutions that make sense and are more than likely cross-browser compliant. I suggest them in my order of my preference:
jQuery w/ jQuery UI
Prototype w/ Scriptaculous
Dojo
Be aware though, that they will take time to understand. I know that when working on a project that is not the top priority.
The fastest way to get started with jQuery and JavaScript in general is here: First Flight. I am not associated w/ codeschool.com in anyway nor do I get any profits from them. This example is free and it is the one that my team passes around at work for people just starting off with jQuery.
I'm assuming your problem is that the user can still submit the form even though the zipcode is invalid.
I'd recommend moving the check into the form submit event like this
<form name = "myform" action="http://www.google.com/" onsubmit = "checkZip()">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
<button id="submit">Submit</button>
</form>
Then you can just return false when the check fails to cancel the submission to google.com