The following function loops through form elements to validate they've been filled in. The bestresult element is optional and if there's no user input, value of 0 should be inserted into to the form element. When I submit the form, fields with empty elements are submitted to the server instead of alerting user to provide values. Any thoughts?
function validateForm()
{
//Validates that form elements are not empty
for(var i=0; i < document.results.elements.length; i++)
{
if(document.results.elements[i].value == null ||
document.results.elements[i].value == "")
{
if(document.results.elements[i] == document.results.besttime)
{
document.results.elements[i].value = 0;
}else
{
alert("Error " + document.results.elements[i].getAttribute("name") + " must be given a value");
return false;
}
}
}
The function itself is fine. I've discovered there's been a problem with a regular expression which is not included in the code snippet
Related
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);
I need to check if there are blank input text fields in my < form >. Instead of doing this multiple times
$.trim($('#myMessage').val()) == '' || $.trim($('#myage').val()) == '' .//so on...
What is the best way to check multiple blank text fields?
use:
if($('input:text[value=""]').length);
try
$("form input[type=text]").filter(function () {
return $.trim(this.value) != "";
}).length;
Note: You have to use any form id or class instead of form
Here is the code ,
// Validate form fields in Sign up form
$(".signup-form").submit(function(){
var isFormValid = true;
$(".signup-form .required input:text").each(function(){ // Note the :text
if ($.trim($(this).val()).length == 0){
$(this).parent().addClass("highlight");
isFormValid = false;
} else {
$(this).parent().removeClass("highlight");
}
});
if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
return isFormValid;
});
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();
}
}
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!");
}
}
I have text boxes where id for these boxes are from 1 to 20. These boxes are created in PHP for loop.
How can i check using javascript if these textboxes are empty. and throw an error on each box.
foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i">
}
Use jQuery?
$('input[type=text]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
or, if there are other inputs you don't want to process:
$('[id^="q_"]').each(function(){if ($(this).val() == '') alert("Your Message Here");});
Without jQuery (and using jQuery would be easier):
foreach(i = 0, i<20, i++)
{
if (document.getElementById('q_' + i).length == 0) {
alert('box ' + i + 'is empty!');
}
}
document.getElementsById('q_'+i)[0].value.length > 0
in a for loop ought to roughly do it.
(though dropping jQuery into your project would probably be a better plan)
Then you could iterate over a class. i.e.
foreach(i = 0, i<20, i++)
{
<input type = "Text" id="q_i" class="q">
}
and in your Javascript:
$("q").each(function(index,object){
if(object.value().length <= 0) alert('empty!');
});
Here is a basic form validation that might be what you're looking for
It uses an invisible error message that shows up when you leave an empty field after you push the button. It doesn't accept white spaces. You can validate it multiple times and it behaves as expected
Here's the jquery part:
$(document).ready(function() {
$("button").click(function()
{ $('span[id^=q_]').addClass("hidden");
$('input[id^=q_]').each(function()
{if ($(this).val().replace(/ /g,'') == '')
{ $("#"+$(this).attr('id')).removeClass("hidden");
}
});
});
});
html part:
<style>.hidden{display:none;}
.visible{display:block;}
</style>
<span id="q_1" class="hidden">Missing text</span>
<input type = "Text" id="q_1">
Not very pretty but it does the job