Issue with JS alert - javascript

I am making a simple form that will throw an alert if a 'hidden' field is being filled but I can't see what I am missing or what syntax I have wrong:
<form method="post" action="http://www.URL/form.php?form=159" id="frmSS159" onsubmit="return CheckForm159(this);">
<input type="text" name="email" value="Email Address" onclick="this.value='';" onBlur="if(this.value=='')this.value='Email Address';" />
<div style="padding: 5px 0;" aria-hidden="true">
<input type="text" name="asdf" tabindex="-1" value="" placeholder="If content, alert error">
</div>
<input type="submit" value="Subscribe" />
</form>
function CheckForm159() {
if ($_POST['asdf'] != '') {
alert("Please type your email address instead of using a form-filler");
}
return true;
}
fiddle

Hi there is mistake in your code...
you added $_POST which is PHP syntax in JavaScript.
Your updated code...
<script>
function CheckForm159() {
var _curValue = document.getElementById('asdf').value;
if (_curValue != '') {
alert("Please type your email address instead of using a form-filler");
}
return true;
}
</script>
<form method="post" action="http://www.URL/form.php?form=159" id="frmSS159" onsubmit="return CheckForm159(this);">
<input type="text" name="email" value="Email Address" onclick="this.value='';" onBlur="if(this.value=='')this.value='Email Address';" />
<div style="padding: 5px 0;" aria-hidden="true">
<input type="text" id="asdf" name="asdf" tabindex="-1" value="" placeholder="If content, alert error">
</div>
<input type="submit" value="Subscribe" />
</form>

Just use the onChange function from JQuery. After the input is changed it will show an alert, like so.
$("input[name=asdf").change(function(){
alert("Input value changed!");
});

Related

Error message will not display after changing the type for a button in form

So I am trying to add validation to a form. Initially, for the button, I had the type as submit, but when I would click on the button the error message for an empty name input would display briefly. I did some research and saw that in order to get the error message to display longer, I needed to change the type to button, which I did. Now, no error messages are showing. I checked the console and there are no errors displaying. Can someone tell me why this is happening and how to fix it?
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
var name = document.regForm.FullName.value;
var nameError = true;
if (name == "") {
printError("nameError", "Please enter your name")
}
};
.error {
color: red;
font-size: 90%;
}
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm()">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<div class="error" id="nameError"></div>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<div class="error" id="emailError"></div>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
</div>
<span id="Message"></span>
<button type="button" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
When the button type is submit the form gets submitted automatically and the function called validation is executed. But when you change the type to button the function will not be called. You have to add click event listener to the sign me up button to call the validate function.
jsFiddle

onsubmit form validation. Form submits even though there are errors

I created a registration page, and each field requires entry and validation. I used the onsubmit event to call my js function to validate the form if the field is empty, however it still submits even though it has not been validated properly.
function validate() {
var streetName = document.getElementById("sN").value;
if (streetName == "" || streetName == null || streetName == undefined) {
window.alert("Sorry");
return false;
}
}
<form name="myForms" action="https://httpbin.org/post " method="post" class="form" onsubmit="return validate()">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" required>
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" required="">
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
// Somemore inputs
<input class="buttons" type="submit" name="submit" value="Sign up" onclick="validate()">
</form>
I expect a window to pop up saying "this entry is wrong and for this reason", but it submits anyway
EDIT: I apologize I should've been clearer in my post. I will use required in some of the inputs, however I will eventually need to write js code to ensure a phone number is all digits and password = passwordconfirm and a postal code is an actual postal code. In the JS file I just showed what I basically tried doing.
Several things
You have validate on the submit AND on the form submit
You should NEVER call anything in a form "submit" since it will hide the submit event/method
You need to get the correct field
Give the form an ID and use unobtrusive code like this
window.addEventListener("load", function() {
document.getElementById("myForm").addEventListener("submit", function(e) {
var errors = false;
var streetName = this.streetname.value.trim(); // no more action needed
if (!streetName) errors = true;
// more validations
if (errors) {
window.alert("Sorry");
e.preventDefault();
}
});
});
<form id="myForm" action="https://httpbin.org/post " method="post" class="form">
<div id="fN">
<label>First Name</label>
<input type="text" name="firstName" placeholder="Enter first name" >
</div>
<br>
<div class="lN">
<label>Last Name</label>
<input type="text" name="lastName" placeholder="Enter last name" >
</div>
<br>
<div class="sN">
<label>Street name</label>
<input type="text" name="streetname" placeholder="Enter your street name">
</div>
<input class="buttons" type="submit" name="SubmitButton" value="Sign up">
</form>
var streetName = document.getElementById("sN").value;
There is no element with that id in the document.
There is an element with sN as its class name, but getElementById won't find an element by its class and the value of <div class="sN"> will always be undefined. It is the input that will have a value.

Fix button to stay disable until user checks a checkbox as well

<form action="add.php" method="post" onsubmit="return ValidationEvent()">
<input type="email" placeholder="Email" class="js-email" name="email" value="<?=formDisplay(getSessionValue("er_email"))?>" required>
<input type="text" placeholder="Zip Code" class="js-zip" name="zip" value="<?=formDisplay(getSessionValue("er_zip"))?>" required>
<input type="text" placeholder="First Name" class="js-name" name="firstname" value="<?=formDisplay(getSessionValue("er_first"))?>" required>
<input type="text" placeholder="Last Name" class="js-lname" name="lastname" value="<?=formDisplay(getSessionValue("er_last"))?>" required>
<input type="password" id="password" placeholder="Password" class="js-pass" name="password" required>
<input type="password" id="confirm" placeholder="Confirm Password" class="js-pass" name="confirm" required>
<span class="textLeft flex alignCenter terms">
<input type="checkbox" name="terms" value="yes" required>
<span>
<span>I agree</span>
</span>
</span>
<span class="textLeft flex alignCenter terms">
<input type="checkbox" name="term" value="yes">
<span>
<span>Keep me posted</span>
</span>
</span>
<center>
<input class="disabled white cbtn1 c1" type="submit" id="submit-btn" value="START MY ORDER" disabled>
</center>
<?php
unset($_SESSION['er_email']);
unset($_SESSION['er_zip']);
unset($_SESSION['er_first']);
unset($_SESSION['er_last']);
?>
</form>
Javascript:
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#submit-btn').attr('disabled', 'disabled').addClass('disabled').removeClass('orangeBtn');
} else {
$('#submit-btn').removeAttr('disabled').removeClass('disabled').addClass('orangeBtn');;
}
});
})()
As you can see from the image, the button gets enabled once you enter all the input fields, I tried with my javascript above for it to also be display until I check "I agree", even if the "keep me posted" was unchecked, but for some reason the it gets enabled before the user clicks "I agree" , how can I fix this?
if empty or checkbox not checked keep it disabled.
if (empty || !$('input[name="terms"]').is(':checked')) {
$('#submit-btn').attr('disabled', 'disabled').addClass('disabled').removeClass('orangeBtn');
} else {
$('#submit-btn').removeAttr('disabled').removeClass('disabled').addClass('orangeBtn');;
}
You are checking if inputs have values. the checkbox has a value "Yes" so it validates as true.
this is because you have skipped if checkbox is checked or not, so you have to add that check too:
var checkbox = $('form > input[type=checkbox]:checked').length;
$('form > input').each(function() {
if ($(this).val() == '' && checkbox == 0 ) {
empty = true;
}
});
This is simple example of how to enable and disable a button.
This might help you implement your logic.
$("#testCheckBox").click(function(){
if(this.checked) {
$("#testBtn").removeAttr("disabled");
} else {
$("#testBtn").prop("disabled", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" id="testCheckBox">
<button id="testBtn" disabled="true">Click It</button>

Why is my form validation not working (onsubmit not triggering)?

I am writing a simple registration screen that allows a user to input their email address and password. As standard, I have the user inputting their email address and password twice to confirm. However, the onsubmit attribute on my form does not seem to be executing.
Here is the code:
Fields
<form name="form" id="form" action="" onsubmit="return validateForm()" class="form col-md-12 center-block" method="POST">
<div class="form-group">
<input type="text" class="form-control input-lg" name="name" id="name" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg" name="email" id="email" placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg" name="cemail" id="cemail" placeholder="Confirm Email Address">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" name="password" id="password" placeholder="Password">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" name="cpassword" id="cpassword" placeholder="Confirm Password">
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" form="form" type="submit" name="register" id="register">Register</button>
<span class="pull-right">Login</span><br>
</div>
</form>
JavaScript
<script>
function validateForm() {
if (isSame(document.getElementById("email"), document.getElementById("cemail"))
&& isSame(document.getElementById("password"), document.getElementById("cpassword"))) {
return true;
} else {
alert("Confirmation fields do not match, please retype and try again.");
return false;
}
function isSame(elementA, elementB) {
if (elementA.value.trim() == elementB.value.trim()) return true;
else return false;
}
//ignore this
function submitForm() {
document.getElementById("form").submit();
}
</script>
I have tried to debug as much as possible, but it doesn't seem like my submit button is triggering the form's onsubmit. I have viewed the request log, and it is posting the data just fine, however.
Thank you in advance!
The indentation of your code is incorrect: you are missing a } at the end of your validateForm function
There's a syntax error; there's no closing bracket for the first function.
Also, your isSame function doesn't need an if statement.
Hopefully this helps:
JS:
function validateForm() {
if(isSame(document.getElementById("email"), document.getElementById("cemail"))
&& isSame(document.getElementById("password"), document.getElementById("cpassword"))) {
return true;
}else{
alert("Confirmation fields do not match, please retype and try again.");
return false;
}
}
function isSame(elementA, elementB) {
return elementA.value.trim() == elementB.value.trim();
}

jQuery's val() returns empty string on bootstrap popover input field

I have a bootstrap popup form with a few input fields. I've added a submit button to the form, that triggers client-side JS validation. However, when the button is clicked, the current value of the input fields is not captured by jQuery's val() method: I just get an empty string.
Here is the markup:
<div class="popover fade right in" style="top: -154.5px; left: 249px; display: block;">
<div class="arrow">
</div>
<h3 class="popover-title">New Job Site contact</h3>
<div class="popover-content">
<form class="popover-form form-horizontal" id="newjobsite_contact_form" accept-charset="utf-8" method="post" action="http://dev.temperature/home/#">
<div class="form-group">
<div class=" required ">
<input type="text" class="form-control" id="popover-first_name" required="1" placeholder="First name" value="" name="first_name">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Phone" value="" name="phone">
</div>
<div class="">
<input type="text" class="form-control" placeholder="Mobile" value="" name="mobile">
</div>
<div class="">
<input type="email" class="form-control" placeholder="Email" value="" name="email">
</div>
<div class="">
<input type="url" class="form-control" placeholder="Website" value="" name="website">
</div>
</div>
<div class="popover_buttons">
<button class="btn btn-success" onclick="submit_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_submit">Submit</button>
<button class="btn btn-warning" onclick="close_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_cancel">Cancel</button>
</div>
</form>
</div>
</div>
Here is the JS:
function submit_newjobsite_contact() {
errors_found = validate_popover_form($('#newjobsite_contact_form'));
if (errors_found.length == 0) {
// Form values submitted to PHP code through AJAX request here
} else {
error_msg = "Please check the following errors:\n";
$(errors_found).each(function(key, item) {
error_msg += "- "+item.message+"\n";
});
alert(error_msg);
}
}
function validate_popover_form(form_element) {
found_errors = [];
$('span.error').remove();
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
console.log($(item).val()); // More validation here, just putting debugging code instead
});
return found_errors;
}
What am I doing wrong? All other attributes for these input fields are being correctly retrieved by jQuery, just not the value after I've typed text into them.
The answer to this problem couldn't be found here because I didn't post the whole source JS, which is too large. What really happened is that I accidentally cloned the popover form, which led to a duplication of the input fields.
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
I Modified it to:
form_element.find('select,input').each(function(key, item) {
if ($(this).data('required') == '1' && $(this).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(this).attr('name'), message: "A value for "+$(this).attr('placeholder')+" is required"});
}
Try using data attributes so instead of using required="1" use data-required="1"
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
so your input should be like this:
<input type="text" class="form-control" data-required="1" placeholder="Surname" value="" name="surname">

Categories