javascript keyup to change divs not just text - javascript

I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});

My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.

Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>

Related

enabled button if password match

here is my script
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
enter.disabled = true;
} else if (user_pass == user_pass2 ){
enter.disabled = false;
} else {
enter.disabled = true;
alert("Your password doesn't same");
}
});
this my html
Password : <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
i am really new in Javascript and jQuery, and this is my first using jquery. i need to make a disabled button if the password doesn't match but, after i put the same password the button is still disabled.
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
//var enter = $("#enter").val();
if (user_pass.length == 0) {
alert("please fill password first");
$("#enter").prop('disabled',true)//use prop()
} else if (user_pass == user_pass2) {
$("#enter").prop('disabled',false)//use prop()
} else {
$("#enter").prop('disabled',true)//use prop()
alert("Your password doesn't same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Password :
<input type="password" name="user[user_pass]" id="reg_pass" required="required">Confirm password
<input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
Use .prop()
You need to set disable attribute like this in jquery $("#enter").attr('disabled',true);
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").attr('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").attr('disabled',false);
} else {
$("#enter").attr('disabled',true);
alert("Your password doesn't same");
}
The .prop( propertyName, value ) allow you set one or more properties for the set of matched elements.
JS
$(function() {
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var confirm_user_pass = $("#reg_confirm_pass").val();
var enter = $("#enter");
if (user_pass.length == 0) {
alert("please fill password first");
enter.prop('disabled', true)
}
else if (user_pass == confirm_user_pass) {
enter.prop('disabled', false)
}
else {
enter.prop('disabled', true)
alert("Your password doesn't match");
}
});
});
HTML
Password: <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password: <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
I believe the other answers are right on target. I set up a simple 'jsfiddle' using jquery and its .prop() method to better illustrate here.
NOTE: I would probably bind to another event to make it fire when changes are made to either input element.
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").prop('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").prop('disabled',false);
} else {
$("#enter").prop('disabled',true);
alert("Your password doesn't same");
}
});
Actually blur will not enable the button instantly, keyup eventhandler does the best job. Here's the below code.
$("#reg_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
$("#reg_confirm_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
Here it responds to the changes in either of the text boxes instantly.
Check it here.
Any better solution than this, please let me know. Thank you.

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Javascript/jQuery form validation

I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:
JavaScript/jQuery
var valid = 0;
function checkName(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
valid++;
}
}
function checkEmail(elem) {
var val = document.getElementById(elem.id).value;
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
valid++;
}
}
function checkMessage(elem) {
var val = document.getElementById(elem.id).value;
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
valid++;
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
function checkSubmit() {
if (valid == 3) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
//If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if (valid < 3) {
document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
HTML Form
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="cform" id="contact-form">
<form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
action="https://Some3rdPartyPOSTService">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
<span id="errorName" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
<span id="errorEmail" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>
<span id="errorMessage" style="margin-left:10px;"></span>
</div>
<span id="errorSubmit" style="margin-left:10px;"></span>
<button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
</form>
</div>
</div>
<!-- ./span12 -->
</div>
</div>
</section>
Simply put your check on onChange event callback, if:
var x = getElementById("formid"); // then add a listener
x.addEventListener('change', function () {
callback with your code that examines the form
});
Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.
Add an onchange event to your text inputs that will remove the error message.
Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.
function checkName(e) {
//gather the calling elements value
var val = $(e.target).val();
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
}
}
function checkEmail(e) {
var val = $(e.target).val();
//Check email format validity
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
}
}
function checkMessage(e) {
var val = $(e.target).val();
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
$('#name').change(checkName);
$('#email').change(checkEmail);
$('#message').change(checkMessage);
function checkSubmit() {
if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
}
/If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.
I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :
document.getElementById("message").addEventListener('keyup', function () {
checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
checkName(this);
});
JSFIDDLE

How come my JavaScript isn't working?

I am doing a login page for school. I have written the page, but the JavaScript does not seem to work with the form. I have checked over both the form and the JavaScript multiple times, but I see no mistake. Can anyone help me?
function processInfo() {
var theusername;
var thepassword;
theusername = document.myForm.username.value;
thepassword = document.myForm.password.value;
if (document.myForm.username.value = "") {
alert("Please enter in the username.")
return false;
} else if (document.myForm.password = "") {
alert("Please enter in the password.")
return false;
} else if (document.myForm.username.value != "andrew123") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (thepassword != "abc") {
document.myForm.txtOutput.value = "Incorrect username or password."
} else if (theusername == "andrew123"
thepassword == "abc") {
document.myForm.txtOutput.value = "Correct! You have successfully logged in."
}
}
<form name="myForm">
<b>User Name:</b>
<input type="text" name="username" size="36" maxlength="100">
<b>Password:</b>
<input type="text" name="password" size="36" maxlength="100">
<p>
<input type=button value="VERIFY INFORMATION" onClick=processInfo()>
</p>
<textarea name="txtOutput" rows=1 cols=4 0></textarea>
</form>
= is an assignment, you keep using it when you are trying to perform a comparison (which would use == or ===).
Sometimes you try to compare the form control with a string instead of getting its .value.
You forgot to put a boolean AND between the two conditions you have theusername == "andrew123"
thepassword == "abc"
You should learn to use the console in your browser as most of these problems would be highlighted in it or could be with the addition of a little logging.

Single else clause for multiple if clauses - javascript

First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.

Categories

Resources