I'm currently creating a mobile website. I'm using jquery mobile.
I've already implemented the login and I'm now working on the registration.
On the login page i've got a simple . On the registration I am then logging the inputs, but it seems that the fields "username" and "password" are empty, even though i've entered some text. This problem doesn't occur after refreshing the page or if I load the page directly from the address bar.
Pageinit is being triggered.
I've deleted the cache but the problem is still there. Does anyone know why this is happening?
Here my code:
<!-- PAGE LOGIN -->
<div data-role="page" id="pageregistration">
<div data-role="content">
<input name="username" id="username" type="text" size="45" maxlength="45" placeholder="Username">
<input name="email" id="email" type="text" size="45" maxlength="45" placeholder="Email">
<input name="password" id="password" type="password" size="45" maxlength="45" placeholder="Password">
<input name="passwordConfirm" id="passwordConfirm" type="password" size="45" maxlength="45" placeholder="Confirm Password">
<button id="register">Create Account</button>
</div>
<script>
$('#pageregistration').on('pageinit', function()
{
$("#register").click(function(e)
{
e.preventDefault();
var username = document.getElementById('username').value;;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var passwordConfirm = document.getElementById('passwordConfirm').value;
console.log("Username: " + username + ", email: " + email + ", password: " + password + " - " + passwordConfirm);
});
});
</script>
</div>
Try with this because pageinit is triggered on the page being initialized, after initialization occurs.
Means you are getting to the registration page from somewhere (Other page)
$(document).on("pageinit", "#pageregistration", function(event) {
// rest of the code
});
The problem was found thanks to Omar. I changed the IDs and everything worked as desired.
Related
I have a reset password form. After submitting it, it redirects to login page. However, it doesn't show any success message upon getting the successful reset password. And, I'm uncertain how can I do this as these are two different jsp files. And even if the login page uses the reset password javascript code, it still can't be able to show the conditional message. I am using java spring boot, jquery and javascript. This is my code:
resetPassword.js
$(".resetPassword").on('submit', function (e) {
e.preventDefault();
var password = $("#pass").val();
var confirmPass = $("#confirmPass").val();
if(password !== confirmPassword){
$(".perror").show();
}
else {
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
});
resetPassword.jsp
<form:form action="/reset_password" method="POST" class="resetPass" modelAttribute="resetPassword">
<div class="alert alert-danger perror" role="alert" style="display: none">Password not match</div>
<form:input type="hidden" path="token" />
<div class="form-group-row ">
<label htmlFor="passwordReset">Password</label>
<input type="password" id="pass" path="password" placeholder="Password" required/>
</div>
<div class="form-group-row ">
<label htmlFor="confirmPasswordReset">Confirm Password</label>
<input type="password" id="confirmPass" placeholder="Confirm Password" required/>
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form:form>
Now, this is the login.jsp in where I want the successful message which currently now I've been showing from alert box however that seems not a good design.
login.jsp
<form:form action="/login" method="POST" modelAttribute="user" >
<div class="alert alert-success successfulResetPassword" role="alert" style="display: none>Your password changed successfully. Please login using your email and password</div>
<input type="text" id="email" name="email" placeholder="email" required/>
<input type="password" id="password" name="password" placeholder="pass" required/>
</form:form>
now all I want, is to show the div class=successfulResetPassword after a user reset the password show that the display alter it's value to visible. But I haven't found any good way to this as reset password is using a different js file and from that submit button I'm redirected the whole scenario to login page. Even if the login page can access that js page still it can't have the value of changing display property :
$("#successfulResetPassword").show();. I tried to modify my code like this till now :
resetPassword.js
else {
$("#successfulResetPassword").show(); //it could've shown the msg, but can't because it's in button submit condition after redirected to login page which has no **resetPassword** class
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
And this is my backend code:
#PostMapping("/reset_password")
public String resetPasswordSubmit(Map<String, Object> model, #ModelAttribute("resetPassword") ResetPasswordDTO resetPassword){
model.put("pageTitle", Constant.PAGE_TITLE);
GenericResponse response = loginService.changePassword(resetPassword);
if(response.getStatusCode() == 200){
return "redirect:/login";
}
model.put("error", "error");
return "resetPassword";
}
I'm having an issue figuring out how to write the following code:
the problem is that I'm using an empty <div> with the id error-display. This <div> is where the error messages will be inserted when the errors that they represent occur. I want to make all fields validated when the user clicks off of them to the next field. If there’s an error, an error message should be displayed. Likewise, error messages should be removed when the user fixes the problem. yet I'm not sure how to do it! here is what I got so far:
<div id="error-display">
</div>
<form id="project-form">
<br>E-mail:<span class="error">* </span>
<input type="email" name="email" id="email" placeholder="Example#example.com" required>
<br>Password:<span class="error">* </span>
<input type="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="password" required>
<br>Confirm Password:<span class="error">* </span>
<input type="password" placeholder="Repeat Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" id="password-confirmation" required>
After inserting the emipty "div id="error-display">" what can I do?
lets say the error message is: Invalid email address.
<input type="email" name="email" id="email" placeholder="Example#example.com" required>
I tried "required" in the input elements and it's working for my inputs, however, I think my professor is looking for a different solution.
I suggest you to add change event listener for every input field and to validate each of them and if some are invalid you should set innerText property of the 'error-display' div to error message text
Here's a quick and simple solution for you
in all of your input fields, put onchange="validateField(fieldID, fieldname)" like this
<input type="email" name="email" id="email" onchange="validateField('email', 'Email')" placeholder="Example#example.com" required>
then paste this script below your form (or you can have this in a separate js file)
<script>
function validateField(fieldID, fieldname) {
var inpObj = document.getElementById(fieldID);
if (!inpObj.checkValidity()) {
document.getElementById("error-display").innerHTML = "Invalid " + fieldname + ":" + inpObj.validationMessage;
} else {
//this will clear your error if the input is already correct
document.getElementById("error-display").innerHTML = "";
}
}
</script>
I'm loading a form into a modal dialog on button click and attaching .ajaxForm() to it on load. ajaxForm() has a beforeSubmit function in which I call two functions to validate username and password fields and setting .setCustomValidity() on them. I imagined it would go something like this; clicking Submit validation is done in beforeSubmit and setCustomValidity is set on invalid fields; then, a message appears on submit attempt.
However, messages appear only after I click Submit the second time. The first time it does nothing.
This is the form.
<form method="POST" action="/scripts/register.php" id="register-form">
<input minlength="6" maxlength="15" type="text" id="user" name="user" oninput="setCustomValidity('')" placeholder="Username" required>
<input minlength="6" maxlength="15" type="password" id="pass" name="pass" oninput="setCustomValidity('')" placeholder="Password" required>
<input minlength="6" maxlength="15" type="password" id="confirm_pass" name="confirm_pass" oninput="setCustomValidity('')" placeholder="Confirm Password" required>
<input type="email" id="email" name="email" placeholder="E-mail" required>
<input type="submit" name="login" class="button" value="Login">
</form>
Loading form into a dialog
$( "body" ).on("click","#register",function(){
$(".modal-dialog").load("register-form.php", function(){
$('#register-form').ajaxForm({
beforeSubmit : function(){
check_password_validity();
check_username_validity();
}
});
});
$( ".dialog-overlay" ).addClass( 'dialog-overlay-open' );
});
And the two functions where I setCustomValidity:
function check_password_validity(){
var pass = $("#pass").val();
var pass2 = $("#confirm_pass").val();
if(!is_alnum(pass)){
$("#pass")[0].setCustomValidity("Samo alfanumerički znakovi, bez razmaka i posebnih znakova.");
return;
}
if(pass!=pass2){
$("#confirm_pass")[0].setCustomValidity("Lozinke se ne podudaraju!");
return;
}
}
function check_username_validity(){
var user = $("#user").val();
if(!is_alnum(user)){
$("#user")[0].setCustomValidity("Samo alfanumerički znakovi, bez razmaka i posebnih znakova.");
return;
}
$.post( "/scripts/check_username_exists.php", {username: user}, function( data ) {
if(data=="true"){
$("#user")[0].setCustomValidity("Korisnik s tim imenom već postoji.");
return;
}
});
}
This works and all, but the messages appear on second submit attempt, after Submit buttons is clicked the second time. It seems like I'm missing something simple but can't figure out what it is.
I have a registration page that requires the user to fill in a noCaptcha reCaptcha, but the widget is not filling in the g-recaptcha-response field. When I submit the form, my Node app is using a script I wrote to submit the response to Google and verify that the captcha is valid. That part is correct, but the recaptcha widget just won't fill out the response textarea it adds to the page. However, the jQuery I wrote that checks the value of the response field lets the page go through if the captcha is checked, but not if it is unchecked like it is supposed to, but the field is still not filled out.
What I need: To find out why reCaptcha isn't filling out the field when I POST the form to my backend.
Below is my register page's code and the jQuery running the page:
<div id="registerCard" class="login-card">
<p class="profile-name-card">Narrify Account Registration</p><br>
<form id="registerForm" action="/register" method="post" role="form" data-toggle="validator" class="form-signin has-validation-callback">
<input type="text" name="firstName" required="" placeholder="First name" autofocus="" class="form-control">
<input type="text" name="lastName" required="" placeholder="Last name" class="form-control">
<input id="inputRegistrationEmail" type="email" name="email" required="" data-validation="email" placeholder="Email address" class="form-control">
<input type="email" required="" data-validation="confirmation" data-validation-confirm="email" placeholder="Email repeat" class="form-control">
<input id="inputRegistrationPassword" type="password" name="password" required="" data-validation="strength" data-validation-strength="2" placeholder="Password" class="form-control">
<input type="password" required="" data-validation="confirmation" data-validation-confirm="password" placeholder="Password repeat" class="form-control">
<div data-sitekey="[MYSITEKEY]" class="g-recaptcha"></div><br>
<button type="submit" class="btn btn-primary btn-block btn-lg btn-signin">Register</button>
</form>
<a id="login-link" href="#" onclick="showLoginForm()" class="forgot-password">Login</a>
</div>
The jQuery:
$(function() {
// Switch to either load an avatar from autocomplete or remove the loading bar
if($("#inputEmail").val() != "") {
updateAvatar();
} else {
$("#image-progress").fadeOut();
}
// Event Handlers for links and inputs
$("#inputEmail").change(updateAvatar);
var url = window.location.pathname;
if(url.substring(url.lastIndexOf("#") + 1) == "register")
showRegisterForm();
$.validate({ modules: "security" });
$("#registerForm").submit(function(e) {
var recaptcha = $("#g-recaptcha-response").val();
if(recaptcha == "") {
e.preventDefault();
alert("Please complete the captcha");
}
});
});
function updateAvatar() {
// Show the loading bar until it is removed by a new image loading
$("#image-progress").fadeIn();
// Set the avatar image based on the input of the Email field
$("#profile-avatar").attr("src", "https://secure.gravatar.com/avatar/" + md5($("#inputEmail").val().toLowerCase()) + "?d=identicon&r=pg");
// Set event handler to hide loading bar once the image loads
$("#profile-avatar").on("load", function() {
$("#image-progress").fadeOut();
});
}
function showResetForm() {
alert("test");
}
function showRegisterForm() {
$("#loginCard").fadeOut();
$("#registerCard").fadeIn();
}
function showLoginForm() {
$("#registerCard").fadeOut();
$("#loginCard").fadeIn();
}
I'm trying to validate login details from an html form. The problem is that the submit button doesn't work with the code. So for example if I leave the username and password blank it won't come up with an alert for "Invalid Username or Password". If I remove type="submit" it works but the button becomes an input text box with an onclick function which does not look good. I was provided with this code as it is a more secure way of passing login details than I had written so I have to confess my ignorance on JS and JSON so apologies if I haven't provided enough info but any guidance would be much appreciated on how to get the button working with the js. This is running on Chrome only. Cheers.
HTML code
<form name="login" id="login-form">
Username<input name="username" id="username" data-bind="value: username" type="text" value="" />
Password<input name="password" id="password" data-bind="value: password" type="password" value="" />
<input name="submit" type="submit" onclick="myApp.getLogin()" value="Login" />
</form>
JS
myApp.getLogin = function(){
var url = "http://localhost:8084/Alumni_JV1/services/login.json?username=" + myApp.vm.username()
+ "&password=" + myApp.vm.password();
console.log(url);
$.getJSON( url, function( data ) {
if(data.response==='success'){
window.location.href="profile.jsp";
}else{
alert("Invalid Username or Password");
}
});
};
A submit button is used to send form data to a server. E.G. <form action='formHandler.php'>. It would submit the form to the current URL if the action attribute isn't defined.
You can get a button without any action with <input type='button' />.
So changing <input type='submit' ... to <input type='button' ... should do the trick :)
Then the code would be:
<form name="login" id="login-form">
Username<input name="username" id="username" data-bind="value: username" type="text" value="" />
Password<input name="password" id="password" data-bind="value: password" type="password" value="" />
<input name="submit" type="button" onclick="myApp.getLogin()" value="Login" />
</form>
Change input type=submit field with button tag.