checking value for element causing error on onsubmit - javascript

I have a form which I am trying to check color of the element before the page submits. I am trying to validate the form using a function called by the from using 'onsubmit='. If I add 'document.getElementById(name).style.backgroundColor' in the code below, when I submit the page it will go directly to the next page without asking if I want to go onto the next page or letting the user know the form has errors. It looks like the form is successfully calling both validate() and check_form() functions, but with the background color check it seems to not complete the validate() function. I've tested it without the 'style.backgroundColor' and it works fine (gives notice to user). What am I doing wrong?
Thanks
Simplified example of the code used:
<!DOCTYPE html>
<html>
<body>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="sample" name="sample" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
var sample = 'sample';
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
if(sample.style.backgroundColor == 'red'){
return 'false';
}
else{
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
test example of check_form function that does work:
function check_form(){
sample = document.getElementById(sample);
return 'false';
}
Edit: The way I have my form set up now is more accurately displayed as:
<!DOCTYPE html>
<html>
<body>
<?php $sample = 'test'; ?>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="<?php echo $sample;?>" name="<?php echo $sample;?>" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
sample = <?php echo json_encode("$sample"); ?>;
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
Where the samples are brought in from another page to dynamically create the form.

sample is a local variable in the dom ready handler which is not accessible in the check form method, but since sample is an id of an element that will be available as a window property(global variable), so you will be getting an error like Uncaught TypeError: Cannot read property 'style' of null.
Instead pass the id as a string literal in the check_form method like
function check_form() {
var sample = document.getElementById('sample');
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
Demo: Fiddle

Related

if jQuery statement | empty text boxes

Ok so i have been literally trying to figure this out for the past hour, its such a simple thing that i never have a problem with. So the input 'username_input' has a jQuery if state that is
if($('#username_input').val() == 0) {
alert('Empty');
} else {
alert('Not empty');
}
After that it moves onto the 'password_input' if statement which is the same thing, but it keeps alerting 'empty'. Why?
<!doctype html>
<html>
<head>
<title> Awflicks </title>
<meta name=viewport content="width=device-width, initial-scale=1">
<link type="text/css" rel="stylesheet" href="index.css">
</head>
<body>
<div id="body_div">
<form action="" method="post">
<div id="username_div"> Username: <input type="text" name="username" id="username_input"> </div>
<div id="password_div"> Password: <input type="password" name="password" id="password_input"> </div>
<div id="retype_password_div"> Retype password: <input type="password" name="retype_password" id="retype_password_input"> </div>
<div type="submit" id="submit_button"> Create Account </div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var $username = $('#username_input').val();
var $password1 = $('#password_input').val();
var $password2 = $('#retype_password_input').val();
function create_account() {
if($username == 0) {
alert('empty');
} else {
alert('not empty')
}
}
$('#submit_button').click(function() {
create_account();
document.forms[0].submit();
})
</script>
</body>
</html>
Because the variable with the value does not get updated when the value changes. It is the value when it is read. You need to read the value when you want it or set the variable onchange.
Also not sure how the value would be zero since there is no value set. Shouldn't you be checking the length? And you are going to want to return a Boolean from your validation function so you know to cancel the form submission.
You can directly use this without defining variables
if(!$('#username_input').val()) // or if(!$('#password_input').val()) for password input
{
alert('empty');
} else {
alert('not empty')
}
You need to refactor as follows to ensure that $username will only store the value once an input has been committed (e.g. once submit has been pressed)
function create_account() {
var $username = $('#username_input').val();
var $password1 = $('#password_input').val();
var $password2 = $('#retype_password_input').val();
if($username == 0) {
alert('empty');
} else {
alert('not empty')
}
}
After you make the changes suggested by the other answers, you are going to have an issue with your form always getting submitted even when the alert shows "Empty". In fact, it will get submitted twice when the alert shows "Not empty". That is because your "submit_button" has type="submit" so it submits the form. You could change to type="button", but my preference is to bind the handler to the form's submit-event, instead of the button's click-event.
$('form').submit(function(event) {
event.preventDefault(); // Stop the form from getting submitted.
var username = $('#username_input').val();
var password1 = $('#password_input').val();
var password2 = $('#retype_password_input').val();
var isValid = true;
if (username == '') {
alert('Empty');
isValid = false;
}
if (isValid) {
this.submit(); // Now submit the form.
}
});

Javascript/PHP Validation

I'm trying to prevent the form being submitted if the validation fails, however its not working at the moment. The onclick method is used for hidden input, but its the onsubmit method that is failing. Any ideas?
<input type="submit" class="btn ccm-input-submit" id="register" name="register" value="Register" onsubmit="return validation(this)" onclick="copytextbox()"/>
<?php echo $form->hidden('rcID', $rcID); ?>
<script>
function copytextbox()
{
var textToCopy = document.getElementById('school').value;
var whereToCopy = document.getElementById('<?php echo $school ?>');
whereToCopy.value += textToCopy;
}
function validation(f)
{
var schoolText = document.getElementById('school').value;
if (schoolText == '') {
alert('Please Choose a value from the dropdown box.');
return false; // stop submission until textbox is not ''
} else {
f.submit();
return false;
}
}
</script>
Also, im attempting to see if that value is a member of an array, I tried using indexOf(schoolText) etc but this also failed, kind regards
Move your onsubmit="return validation(this)" attribute from the <input> tag to the <form> tag.
Test an array like this:
// global array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function findFruit(val) {
if(fruits.indexOf(val) == -1 {
alert('not found');
} else {
alert('Found!')
}
}
findFruit('Peach'); // not found

function not working in jsp page?

<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length

stopping form submit if the validation fails.

I am validating the dates in below function. If the validation fails, then the form should not get submitted. I tried returning false in form onsubmit but it still gets submitted. However, Validation is working fine and getting the alert that I put in the function. Any help to stop submitting the form if validation fails.
<script>
function dateCheck()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
document.getElementById('name4').focus();
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setFullYear(parse_sDate.getFullYear() + 1);
if(parse_eDate >= parse_sDate)
{
alert("End date should not be greater than one year from start date");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return dateCheck()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
Just a comment:
If your listener passes a reference to the form, you can access the controls by name or ID:
<form onsubmit="return dateCheck(this)">
then:
function dateCheck(form) {
var start = form.name3.value;
...
}
Note that you should declare variables, otherwise they will become global at the point they are assigned to. Also, you should check the values in the controls before passing them to the compare function (and display a message asking the user to enter a valid value if they aren't).
function dateCheck(form) {
var start = form.name3.value;
var end = form.name4.value;
var valid = compare(start, end);
if (!valid) form.name4.focus();
return false;
}
I appreciate all contributions above. I have just applied the suggestions above to solve my challenge & it works fine. Keeping it simple I use the following:
<form id="newuser" action="newuser.php" onsubmit="return pswderr(this)">
For the button I have
<input id='submit' type="submit" value="Login" onClick="return pswderr();">
My script is:
<script>
function pswderr() {
var pswd1 = document.getElementById("newuserpswd").value;
var pswd2 = document.getElementById("rptpswd").value;
if (pswd1 !== pswd2) {
document.getElementById("alarm").innerHTML = "Password and password
verification do not match. Retry";
return false;
} else {document.getElementById("alarm").innerHTML = "";
return true;
}
}
</script>
use return on the onclick attribute in the form tag attribute onsubmit="return validateForm()" , if you return false in your validation function in javascript if the input is incorrect then you have to add return to your onclick attribute in order for it to execute .Hope it helped someone!
<script>
function validateForm(){
var validation = false;
var phonenumber = document.forms["enqueryForm"]["phonenumber"].value;
if(phonenumber != 11) {
alert("phonenumber is incorrect");
//e.preventDefault();
return false;
}
}
</script>
<form class="form-style-5" action="BookingForm.php" method="post" id="bookingForm" onsubmit="return validateForm()" name="enqueryForm">
<input type="tel" name="phonenumber" placeholder="your no.">
<input type="submit" name="submit" value="submit">
</form>
return is not going to stop the form from submit if its called in a subfunction e.g. compare(sDate, eDate)
so change your function to this
function dateCheck(e){
var start = document.getElementById('name3').value;
var end = document.getElementById('name4').value;
if(compare(start, end)) {
// no error submit i guess
// return true ?
} else {
// error with date compare
return false;
}
end.focus();
}
In my case i used pattern in input field and also gave maxlength.
What worked with me was, remove Length attribute from input field
you can achieve the same thing using jQuery Form Plugin.
$(document).ready(function() {
$('#your_form_id').ajaxForm( { beforeSubmit: dateCheck } );
});
- I hope this will help you : Just write this code on your Html/jsp page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
- **Don't forget to add this on your html page**
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
//option A
$("regF").submit(function(e) { //regF is form id
alert('submit intercepted');
e.preventDefault(e);
});
});
</script>
</html>

javascript form validation object

Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.

Categories