Check if two fields has the same value with javascript - javascript

I want to make a form for registration and the form should have two fields for password, so there is no mix up.
So if the passwords are the same, there should be a green bock right to the field, and if not there should be a red cross..
So here is my code for testing, but it doesn't work.
<script language="javascript" type="text/javascript">
function check()
{
var loc;
if (test.name1.value == test.name2.value) {
loc = "/img/greenbock.jpg";
}
if (test.name1.value != test.name2.value) {
loc = "/img/redcross.jpg";
}
return loc;
}
</script>
</head>
<body>
<form name="test" method="post" action="">
Name<br />
<input name="name1" type="text" /><br />
Name agian<br />
<input name="name2" type="text" onblur="check()" />
<script language="javascript" type="text/javascript">
if(loc != "")
{
document.write("<div style=\"height:19px; width:20px; background-image:url("+ loc + ")\"></div>");
}
</script>
<br />
Username<br />
<input name="username" type="text" /><br />
So where am I wrong? A little fault or, should i thruw everything away?
[edit]
Now I have set the check-function to run the script after input. So now its doing samething, because everything disapears.. Solutions?

My suggestion would be to let the style of the error/success images be controlled with CSS. Then your validation function can decide what CSS class to assign to a <div> sitting next to your input fields.
Additionally, you will need to add the check() to the other name input in case the user returns to either field later and makes a change.
CSS
/* Shared styling */
.validation-image {
height:19px;
width:20px;
display: none;
}
/* Error styling */
.validation-error {
background-color: #ff0000;
background-image: url('/img/redcross.jpg');
}
/* Success styling */
.validation-success {
background-color: #00ff00;
background-image: url('/img/greenbock.jpg');
}
HTML
<form name="test" method="post" action="">Name
<br />
<input name="name1" type="text" onblur="checkNames()" />
<br />Name agian
<br />
<input name="name2" type="text" onblur="checkNames()" />
<div id="nameValidation" class="validation-image"></div>
<br />Username
<br />
<input name="username" type="text" />
<br />
</form>
JavaScript
function checkNames() {
// Find the validation image div
var validationElement = document.getElementById('nameValidation');
// Get the form values
var name1 = document.forms["test"]["name1"].value;
var name2 = document.forms["test"]["name2"].value;
// Reset the validation element styles
validationElement.style.display = 'none';
validationElement.className = 'validation-image';
// Check if name2 isn't null or undefined or empty
if (name2) {
// Show the validation element
validationElement.style.display = 'inline-block';
// Choose which class to add to the element
validationElement.className +=
(name1 == name2 ? ' validation-success' : ' validation-error');
}
}
Of course, this is a lot more code than you had before, but you could turn this into a re-usable function pretty easily.
jsFiddle Demo

Try this, document.test.name1.value or document.forms["test"]["name1"].value instead of test.name1.value
should be
var loc;
var name1=document.forms["test"]["name1"].value;
var name2=document.forms["test"]["name2"].value;
if(name1== name2){
loc = "/img/greenbock.jpg";
}else {
loc = "/img/redcross.jpg";
}

Related

Unable to produce output from span tag

I am working on a simple form from a coursera MOOC on web development. I am using a RegEx in JS to test for valid input, and an onblur effect to display my test' output. For some odd reason it's not working. Here is the code, I'll explain what it does:
<!DOCTYPE HTML>
<html>
<head>
<title>Week 5 Assignment - Simple Form</title>
<script type="text/javascript" src="Week5.js"></script>
</head>
<body> <!--The Five Input Elements here are as follows
1. Text Box
2. Text Box
3. Radio Buttons
4. Date
5. Button-->
<form>
First Name:<br />
<input type="text" name="firstname" onblur="testFirstName(); "/><span id="firstNamePrompt"> </span><br /><br />
Last Name:<br />
<input type="text" name="lastname" onblur="testLastName(); "/><span id="lastNamePrompt"></span> <br /><br />
Gender:<br />
<input type="radio" name="gender" value="male" />Male<br />
<input type="radio" name="gender" value="female" />Female<br /><br />
Date and Year of Birth:<br />
<input type="date" name="dob" /><br /><br />
<input type="button" value="Submit" />
</form>
</body>
</html>
Here, I am creating a simple form and the onblur event is triggered by 2 javascript functions, testFirstName() and testLastName(). I expect to get output on the same line as the textboxes that state that a condition has been or has not been met.
Here is the JavaScript:
function testFirstName() {
var firstName = document.getElementById('firstname').value;
var regCheck = /^[a-zA-Z\s\'\-] {2,15} $/;
if (regCheck.test(firstname)) {
document.getElementById('firstNamePrompt').style.color = "green";
document.getElementById('firstnamePrompt').innerHTML = "<strong>Name Accepted!</strong>";
return true;
}
else {
document.getElementById('firstNamePrompt').style.color = "red";
document.getElementById('firstNamePrompt').innerHTML = "<strong>Name must be between 2-15 characters!</strong>";
return false;
}
}
function testLastName() {
var firstName = document.getElementById('lastname').value;
var regCheck = /^[a-zA-Z\s\'\-] {2,25} $/;
if (regCheck.test(firstname)) {
document.getElementById('lastNamePrompt').style.color = "green";
document.getElementById('lastnamePrompt').innerHTML = "<strong>Name Accepted!</strong>";
return true;
}
else {
document.getElementById('lastNamePrompt').style.color = "red";
document.getElementById('lastNamePrompt').innerHTML = "<strong>Name must be between 2-25 characters!</strong>";
return false;
}
}
I have a reg. expression that tests that characters can only be A-Z (upper and lowercase), Have a space via the 's', or have an apostrophe or a dash in the name. Those are the only allowed characters based on the regex. I am not sure why I don't see text "Name Accepted!" or "Name must be between x & y characters". Please let me know if there is anything else I need to explain. I hope this is not verbose.
An element needs to have and id in order to be able to target it from javascript with document.getElementById().
After adding an id to firstname and lastname everything works fine.
Also your span ids have upper case letters, which you didn't mention in your javascript.
Here is the corrected code: (run the snippet)
function testFirstName() {
var firstName = document.getElementById('firstname').value;
var regCheck = /^[a-zA-Z\s\'\-]{2,25}$/;
if (regCheck.test(firstName)) {
document.getElementById('firstNamePrompt').style.color = "green";
document.getElementById('firstNamePrompt').innerHTML = "<strong>Name Accepted!</strong>";
return true;
}
else {
document.getElementById('firstNamePrompt').style.color = "red";
document.getElementById('firstNamePrompt').innerHTML = "<strong>Name must be between 2-15 characters!</strong>";
return false;
}
}
function testLastName() {
var lastName = document.getElementById('lastname').value;
var regCheck = /^[a-zA-Z\s\'\-]{2,25}$/;
if (regCheck.test(lastName)) {
document.getElementById('lastNamePrompt').style.color = "green";
document.getElementById('lastNamePrompt').innerHTML = "<strong>Name Accepted!</strong>";
return true;
}
else {
document.getElementById('lastNamePrompt').style.color = "red";
document.getElementById('lastNamePrompt').innerHTML = "<strong>Name must be between 2-25 characters!</strong>";
return false;
}
}
<!DOCTYPE HTML>
<html>
<head>
<title>Week 5 Assignment - Simple Form</title>
<script type="text/javascript" src="Week5.js"></script>
</head>
<body> <!--The Five Input Elements here are as follows
1. Text Box
2. Text Box
3. Radio Buttons
4. Date
5. Button-->
<form>
First Name:<br />
<input type="text" id="firstname" name="firstname" onblur="testFirstName(); "/><span id="firstNamePrompt"> </span><br /><br />
Last Name:<br />
<input type="text" id="lastname" name="lastname" onblur="testLastName(); "/><span id="lastNamePrompt"></span> <br /><br />
Gender:<br />
<input type="radio" name="gender" value="male" />Male<br />
<input type="radio" name="gender" value="female" />Female<br /><br />
Date and Year of Birth:<br />
<input type="date" name="dob" /><br /><br />
<input type="button" value="Submit" />
</form>
</body>
</html>
In order to use getElementById method, you should provide the id attribute to your inputs:
<input type="text" id="firstname" name="firstname" onblur="testFirstName(); "/>
And
<input type="text" id="lastname" name="lastname" onblur="testLastName(); "/>

Javascript/jQuery Submit Form Validation

I am new to web development and I am trying to create a simple form validation using javascript/jquery.
I drafted a simple form very similar to what I have that looks like this:
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$('.price')[i].focus();
}
errors = 'True';
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!
You can add a class to the inputs with bad values. The class can add a border for example.
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$(inputs[i]).addClass('error');
errors = 'True';
} else {
$(inputs[i]).removeClass('error');
}
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.
<form id="price-form" action="" method="get">
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<button type="submit">Save</button>
</form>
Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?
$(function() {
$('#price-form').on('submit', function(e) {
// this variable acts as a boolean, so might as well treat it as a boolean
var errors = false;
// remove previous errors
$('.price').removeClass('error');
// check each input for errors
$('.price').each(function() {
if (isNaN(this.value)) {
$(this).addClass('error');
errors = true;
}
});
// alert if there are any errors
if (errors) {
alert('Errors are highlighted!');
e.preventDefault(); // stop submission
}
});
});
In your CSS, you could do
.error {
border: 2px solid #a00;
}

How to validate a php form with java script, that is on everypage of my site

The problem i'm having is Im trying to get the contact.php to validate a contact form that is now in the bottom of every page in my site. It worked great with just validating one page and having a hard URL to take them back to. the troubleing code is this.
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['HTTP_REFERER'].$report);
}else{$report='noerror';}
Ive also tryed this:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['PHP_SELF'].$report);
}else{$report='noerror';}
This is the original code that worked for one page:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header('Location:estimate_page.php?'.$report);
}else{$report='noerror';}
I could just make a new "contact.php" page for every page that has the form in the footer, but thats stupid if i can just make this work. Any ideas
You are thinking in the right direction with javascript/jQuery -- it will allow you to catch the invalid fields before submitting / changing pages. Much better user experience. Only submit when fields are validated.
Here is a link for how to do simple field validation testing with jQuery:
jsFiddle Demo
HTML:
One: <input type="text" id="f1"><br />
Two: <input type="text" id="f2"><br />
Three: <input type="text" id="f3"><br />
Four: <input type="text" id="f4"><br />
<br />
<input type="button" id="mybutt" value="Go" />
javascript/jQuery:
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
}
}); //END mybutt.click
Note that the above example uses jQuery, so you must reference the jQ libraries (usually inside the head tags, something like this:)
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
EDIT:
Here is what the full HTML would look like:
<?php
//Any initial PHP code goes here
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//javascript
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$(document).ready(function() {
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
return false;
}
//If it gets to here, it passed validation
$('#yourForm').submit();
}); //END mybutt.click()
}); //END $(document).ready()
</script>
</head>
<body>
<form id="yourForm">
One: <input type="text" id="f1" /><br />
Two: <input type="text" id="f2" /><br />
Three: <input type="text" id="f3" /><br />
Four: <input type="text" id="f4" /><br />
</form>
<input type="button" id="mybutt" value="Click Me">
</body>
</html>
Note that, using the above scenario, no further PHP code would execute until the form is submitted, using the manual $('#yourForm').submit(); statement.

Dynamically changing which button is pressed with "enter"

I have a form with two buttons and some text inputs. By default if you press enter it will "click" the first button. I'd like to make it so that if you type in either of the text boxes, if you press enter the second button will be the one to be clicked.
In the simplified example below, pressing enter will by default "click" the log in using facebook button. This will happen even if something is entered in the email or password text inputs. I'd like it so that if something is entered in either the email or password inputs, then pressing enter will "click" the login with email/password button.
<form>
<button class="login-facebook">Log in with Facebook</button>
<input type="text" class="email" placeholder="email"><br>
<input type="password" class="password" placeholder="password"><br>
<button class="login-password">Log in with email/password</button>
</form>
Goal is something like:
$('.email').add('.password').on('change', function() {
$('.login-password').setToBeNewDefaultClickIfEnterIsPressed();
});
Where setToBeNewDefaultClickIfEnterIsPressed() changes the default enter.
See: Multiple submit buttons on HTML form – designate one button as default
You can also make them separate forms and play with that. See also: preventDefault
Try this.
I threw in a field that let's you select the button you want to be the default, just to show how it works. If that field is empty, I made the default button #2.
jsFiddle here
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var defaultbutt = 2;
$(document).ready(function() {
$('[id^=txt]').blur(function() {
if ($(this).val() != '') {
defaultbutt = $('#pickabutt').val();
if (defaultbutt=='') defaultbutt = 2;
}
});
$('#pickabutt').blur(function() {
defaultbutt = $('#pickabutt').val();
if (defaultbutt=='') defaultbutt = 2;
});
$(document).keypress(function(e) {
if(e.which == 13) {
$('#mybutt' + defaultbutt).click();
}
});
$('[id^=mybutt]').click(function() {
var num = $(this).val();
alert('You clicked button: ' + num);
});
}); //END $(document).ready()
</script>
</head>
<body>
Login:<br /><input id="txtLogin" type="text" /><br />
PWord:<br /><input id="txtPassword" type="password" /><br />
<input type="button" id="mybutt1" value="One" />
<input type="button" id="mybutt2" value="Two" />
<input type="button" id="mybutt3" value="Three" />
Default button Number:<br /><input id="pickabutt" type="text" /><br />
</body>
</html>

Check all input fields have been filled out with jQuery

I have 3 divs, each with a dfew input fields and next button on.
I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fields WITHIN the same div as the button, are not null.
I've tried the following with no luck but Im 100% certain its wrong, only I cant find the relevant information online...
http://jsfiddle.net/xG2KS/1/
You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:
$(".next").click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
//At least one input is empty
}
});
Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.
Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.
Here's an updated fiddle.
$('.next').click(function() {
var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });
if (emptyInputs.length) {
alert('Fail!');
}
});
Because there is no jQuery selector for this case you can extend jQuery’s selector capabilities.
Assuming you select all :text elements, the extension is:
$.extend($.expr[':'],{
isEmpty: function(e) {
return e.value === '';
}
});
Hence, you can select all empty text fields:
$(this).closest('div').find(':text:isEmpty');
$.extend($.expr[':'], {
isEmpty: function (e) {
return e.value === '';
}
});
$('.next').click(function () {
var missingRequired = $(this).closest('div').find(':text:isEmpty');
console.log('Empty text fields: ' + missingRequired.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
$('.next').click(function() {
var inputs = $(this).parent().find('input[value=""]');
if (!inputs.length) {
// you have empty fields if this section is reached
}
});

Categories