The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of alert and onFocus. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
A better way to do this is using the input event. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the validateRequiredField function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines what to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
Not tested but you can try this
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);
Related
Im trying to submit a form by javascript, after a specific field is validated.
im using
function doValidate(){
var error = false;
var nr = document.getElementById('number').value;
if (nr > '10'){
document.getElementById('number').className += " red";
error = true;
}
if (error = false) {
document.forms["new_qs"].submit();
}
}
but when error is false, just nothing happens!
I inspected the site with firebug, error is false, the document.forms seems to do nothing.
But in Online Tutorials this is working very good.
Here is a complete fiddle from the site http://jsfiddle.net/S7G9J/25/
What could be the problem/solution?
if (error = false) {
In the above, you are using assignment operator. =. Use == to compare
Also you are comparing string instead of numbers.
Try this:
function doValidate(){
var error = false;
var nr = Number(document.getElementById('number').value);
if (nr > 10){
document.getElementById('number').className += " red";
error = true;
}
if (error === false) {
document.querySelector('[type="button"]').submit();
}
}
The error lies in the line where you submit() the form.
In your fiddle, your form's id is "test". In your javascript, the form you're referencing should have an id of "new_qs". However, there is no such form, so there is no submit() processed.
document.forms[0].submit() will submit the first form in order of appearance in your HTML. So, try this:
function doValidate(){
var error = false;
var nr = document.getElementById('number').value;
if (nr > '10'){
document.getElementById('number').className += " red";
error = true;
}
if (error == false) { // need double equal here
document.forms[0].submit();
}
}
function send() {
alert("Your message sent.");
}
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue != "" && messageValue != "") {
document.getElementById("af-form").submit();
} else {
alert("Nickname or message is blank. Please fill.");
return false;
}
}
These are my JS codes
<input type="text" name="nickname" id="input-nickname" required>
<textarea name="message" type="text" id="input-text" required></textarea>
<input type="submit" value="Send" onclick="wrongNickNameorMessage() + send()" />
And these are my HTML codes.
When I click on Send button. First alert("Your message sent."); then alert("nickname or message is blank. Please fill."); is working. Or exact opposite.
I wanna disabled send() function if wrongNickNameorMessage() is true.
How can I do that?
You have the right idea but you're going about it very out-of-the-way. Try this:
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue === "" || messageValue === "") {
alert("Nickname or message is blank or improper input detected. Please fill.");
return false;
}
document.getElementById("af-form").submit();
alert("Your message sent.");
}
You dont need the other function or the other part of the if statement since you're just validating input. You can get more creative but that's all you really need. Your function will completely stop if there's a problem but otherwise, it'll show the right message and submit.
Although your practice is horrible, this may help you in the future:
/* first give your submit button an id or something and don't use the onclick
attribute
*/
<input type='submit' value='Send' id='sub' />
// Now the JavaScript, which should be external for caching.
var doc = document;
// never have to use document.getElementById() again
function E(e){
return doc.getElementById(e);
}
function send() {
alert('Your message was sent.');
}
// put all your sub onclick stuff in here
E('sub').onclick = function(){
var nicknameValue = E('input-nickname').value;
var messageValue = E('input-text').value;
if(nicknameValue !== '' && messageValue !== '') {
send(); E('af-form').submit();
}
else {
alert('Nickname or message is blank. Please fill.');
return false;
}
}
Note, that this is not sufficient to handle a form. It just shows concept. JavaScript can be disabled, so you must account for that as well, Server Side.
You need to call a wrapper method that will call the wrongNickNameorMessage() check result and than continue only if returned true.
function conditionalSend(){if (wrongNickNameorMessage()){send();}}
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}
Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
$(".error").show(500);
}else{
$(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.
I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}