error blinks when submit button is clicked - javascript

i made a sign up form in which if you keep name or last name input it shows a error written byside of the input i did the same in radio input.every thing is working but,the problem is
when the submit button is clicked the errors blinks and go away. the button type is submit
i am writting the code down
function SignUp() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").text();
var date = $("#dd option:selected").text();
var month = $("#mm option:selected").text();
var yy = $("#yy option:selected").text();
var sex = $("input:radio[name=sex]:checked").val();
if ($.trim($("#firstname").val()) == "") {
document.getElementById("firstnameerror").innerHTML = "Please write firstname";
if ($.trim($("#lastname").val()) == "") {
document.getElementById("lastnameerror").innerHTML = "Please write lastname";
if (!$("input[name='sex']:checked").val()){
document.getElementById("gendererror").innerHTML = "Please select your gender";
}
}
}
}

You problem is that you don't prevent default behavior of the form which is submiting. Try this (simplified code):
function SignUp(e) {
var firstname = $("#firstname").val();
var lastname = $("#lastname").text();
if ($.trim($("#firstname").val()) == "") {
$("#firstnameerror").text("Please write firstname");
e.preventDefault(); // <!-- prevent form submit in case of errors
}
else {
$("#firstnameerror").text('');
}
if ($.trim($("#lastname").val()) == "") {
$("#lastnameerror").text("Please write lastname");
e.preventDefault();
}
else {
$("#lastnameerror").text("");
}
}
$('#form').submit(SignUp)
http://jsfiddle.net/fh6Ar/
Also don't bind click events to submit buttons. Form has special event for this submit event.

When you call SignUp() function as your submit button is clicked you must return false for the form to not be submitted.
With jquery you could easily do:
$('#submitButtonId').click(function(){
SignUp();
return false;
})
If all goes right after the javascript validation you could do:
$(#myFormId).submit();
Or just plain:
<input type="submit" name="send" value="SEND" onclick="SignUp(); return false;" />

Related

Onclick and jQuery click working together but return false not working in jquery

Onclick and jQuery click working together but return false not working in jquery. I want to validate fields before on onclick open next page. Problem with my code is that if filed are blank in that case it open next page. I use return false in each empty case. So until all fields are not filled up. next page should not open.
Html Code
<button id="onepage-guest-register-button" type="button" class="button secondary" onclick="$('login:guest').checked=true; checkout.setMethod();"><span><span><?php //echo $this->__('Checkout as Guest') ?></span></span></button>
jQuery Code
jQuery('#onepage-guest-register-button').click(function(e){
var email=jQuery('#login-email').val();
jQuery('.validate-email').attr('value', email);
var login_name = jQuery('#login_name').val();
var login_phone = jQuery('#login_phone').val();
var login_email = jQuery('#login_email').val();
alert("name"+login_name+'phone'+login_phone+'email'+login_email);
if(login_name==''){ jQuery('.login_name').text('Please enter full name'); return false; }else{ jQuery('.login_name').empty();}
if(login_phone==''){ jQuery('.login_phone').text('Please enter Phone Number');return false;}else{ jQuery('.login_phone').empty();}
if(login_email==''){ jQuery('.login_email').text('Please enter Phone email');return false;}else{ jQuery('.login_email').empty();}
//alert('trigger');
jQuery('#onepage-guest-register-button').trigger('onclick');
});
Don't mix onclick attribute with onclick event handler. It's just plain silly.
In most cases, it's better to go with the latter.
1) Remove onclick attribute
<button id="onepage-guest-register-button" type="button" class="button secondary"><span><span><?php echo $this->__('Continue') ?></span></span></button>
2) Move the logic into your onclick event handler.
jQuery('#onepage-guest-register-button').click(function(e){
// no idea
var email = jQuery('#login-email').val();
jQuery('.validate-email').attr('value', email);
// get values
var login_name = jQuery('#login_name').val();
var login_phone = jQuery('#login_phone').val();
var login_email = jQuery('#login_email').val();
// flag if errors is found; assume no errors by default
var err = false;
// clear errors?
jQuery('.login_name').empty();
jQuery('.login_phone').empty();
jQuery('.login_email').empty();
// show errors if any
if (login_name == '') {
jQuery('.login_name').text('Please enter full name');
err = true;
}
if (login_phone == ''){
jQuery('.login_phone').text('Please enter Phone Number');
err = true;
}
if (login_email == ''){
jQuery('.login_email').text('Please enter Phone email');
err = true;
}
// do the appropriate action depending if there are errors or not
if (err) {
return false;
} else {
$('login:guest').prop('checked', true);
checkout.setMethod();
}
});

Javascript form validation code looping

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);

Either Can Not submit(); form in jQuery, or can not check if input fields are filled out

I am having trouble submitting the below form.
For background, I'm trying to "submit" a form for a delivery, and I need to know a) their pickup address, b) their dropoff address, and c) their description. I created <p class="error"> fields if those <input>s are empty (as in "Please enter a description").
If I remove the 'return false;' the form submits no matter what, but if I keep the 'return false;' the jQuery works (i.e. - error message appears) but now the form NEVER submits. Thoughts?
Here's my main.js
var main = function() {
$('form').submit(function() {
var pickup = $('#pickup').val();
if(pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if(dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if(description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
return false;
});
};
$(document).ready(main);
var main = function () {
$('form').submit(function () {
var pickup = $('#pickup').val();
if (pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if (dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if (description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
// did not pass validation
if (pickup != "" || dropoff != "" || description != "") {
return false;
}
// passed validation, submit
return true;
});
};
$(document).ready(main);

Why doesn't my reset() function remove my red error lines?

function validate() {
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if (checkfname() == true) {
alert("Entry submitted.");
} else {
return false;
}
}
function checkfname() {
var fname = document.getElementById("fname").value;
if (fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
} else if (!isNaN(fname)) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
} else {
return true;
}
}
function addRow() {
if (validate() == true) {
}
}
<form>
First Name:
<input type="text" id="fname" name="fname" />
<p id="errorfname" class="red"></p>
<input id="submit" type="submit" value="Submit Entry" onclick="return addRow()" />
<input id="clear" type="button" value="Reset" onclick="reset()" />
</form>
<form>
<fieldset>
<label for = "firstnameinput">
First Name: <input type = "text" id = "fname" name = "fname" placeholder = "John"/>
<p id = "errorfname" class = "red"></p>
</label>
</fieldset>
<fieldset>
<label id = "submitbutton">
<input id = "submit" type = "submit" value = "Submit Entry" onclick = "return addRow();upperCase();"/>
</label>
<label id = "resetbutton">
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
</label>
</fieldset>
</form>
This is my simplified HTML file. It basically has an input and a paragraph below it to display an error message later on. For now it is set as "" in javascript. The HTML also has a submit button and a reset button. The purpose of the reset button is to clear all previously entered fields or any error message that has appeared.
function validate(){
var fname = document.getElementById("fname").value;
document.getElementById("errorfname").innerHTML = "";
if(checkfname() == true){
alert("Entry submitted.");
}
else{
return false;
}
function checkfname(){
var fname = document.getElementById("fname").value;
if(fname.length == 0) {
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot be empty.";
return false;
}
else if(!isNaN(fname)){
document.getElementById("errorfname").innerHTML = "Invalid first name. Cannot contain numbers.";
return false;
}
else{
return true;
}
}
function addRow(){
if(validate() == true){
event.preventDefault();
var fname = document.getElementById("fname").value;
firstNameArray.push(fname)
var row = document.getElementById('table').insertRow(-1);
var colNum = row.insertCell(0);
var colName = row.insertCell(1);
i++;
colNum.innerHTML = i;
colName.innerHTML = fname + " " + lname;
else{
return false;
}
reset();
}
Lastly, my reset() function below.
function reset(){
document.getElementById("errorfname").innerHTML = "";
document.getElementById("fname").value = "";
}
The problem is, for example, in the input box for fname, I enter John. When I press the reset button on my HTML which calls the reset() function, John in the box disappears so I got that going for me which is nice. However, lets say I purposely left the box blank to receive an error message, a red sentence below the box appears saying "Invalid first name. Cannot be empty." When I press the reset button to call onto the reset() function, this red error message does not disappear however, any current value inside the box disappears. This makes by reset() function work 50% only. I clearly stated for both to disappear in my reset() function.
TL;DR
I have a reset button in my HTML which calls a reset() function in my javascript. I have a name input box in my HTML and what the reset() function is supposed to do is to remove any current name which is inside the box as well as remove any error message that appears below. My reset() function is able to clear away any name inside the box currently but is unable to clear away the error message.
I created a fiddle to test your problem. I noticed the same thing. I changed the method reset() to resetTest() and it worked fine.
working fiddle
The reason changing the name worked is that onxyz= attribute event handlers are run (effectively) within a couple of with statements, one of which is with (theEnclosingFormElement). Form elements have a built-in reset method that clears all of their inputs to their initial values. So in this:
<input id = "clear" type = "button" value = "Reset" onclick = "reset()"/>
The reset being called isn't your reset, it's the form's reset, which doesn't (of course) do anything with errorfname. Changing the name removes the conflict.

How do I use javascript to prevent form submission because of empty fields?

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!");
}
}

Categories