make a simple login page - javascript

hey all..
i want to make a simple login page. I have prepared two textfield.
<input type="text" id="user">
<input type="password" id="password">
<input type="button" id="go">
i want after click #go script can check:
if #user value != "admin"
then #password value != "qaubuntu"
will show and JS alert.
but if data same, will show some hidden .
can you show me how to do that?

$(function() {
$('#go').click(function() {
if($('#user').val() !== "admin" || $('#password').val() !== "qaubuntu") {
alert('Invalid login');
return false;
} else {
return true;
}
});
});
that's the quick fix (assuming you're just playing around). But you should never do it like this for a few reasons:
Anyone with half a brain can look at your JavaScript and see what the id/pw is
I always think it's better to do the user authentication at the server side
Probably a million others, it's so insecure it hurts
but for the purpose of this answer I'm assuming you're just practising with jQ.

this is in jquery, when clicking on button #go check the login data
$('#go').bind('click',function()
{
if($('#user').val() == 'admin' && $('#password').val() == 'qaubuntu'))
//ok do what you need
else
alert('username or password not valid');
});

Related

Having error with simple login form,please resolve my issue and also mention the problem

I am trying to make an simple login form using javascript,also don't able to find any error,please help me to succesfully implement it.Here is code
function validate()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "admin" && password == "user")
{
alert("login successfully");
return false;
}
else
{
alert("login failed");
}
}
It seems like your code should be working fine, unless you've incorrectly trying to access the "username" and "password" elements. In which case, your program will not throw an error. I would suggest handling that error appropriately, which you can see in the following answer: https://stackoverflow.com/a/20378738/8222441.
If an error does exist with trying to reference your desired elements by its ID, you can console.log something to debug further!
Nothing here seems to be broken. I'm guessing something is wrong with your html, but I can't tell since it's not included.
Here's a way of doing it, this works:
<form id="loginForm">
<input placeholder="username" id="username" />
<input placeholder="password" id="password" />
<button type="submit" id="submitButton">Submit</button>
</form>
const form = document.getElementById("loginForm")
form.addEventListener("submit", (e) => {
e.preventDefault();
if(form.elements["username"].value == "admin" && form.elements["password"].value == "user"){
alert("login successful")
} else {
alert("nope")
}
})

Prevent Form from Submitting if there are Errors

Before I get into the problem details, I still need to tell you about this form I am creating. I have a Registration form and once the user submits the form by clicking the Submit button, it will NOT go directly to a Successfully Registered page. The user will be seeing a Confirmation page prior to that. In this page, the user will see all the data he inputted for him to review. Below it are the Confirm button and the Return button (if user still likes/needs to edit his details, it will then show the form for him to edit once this button is clicked). But here's the thing, the Registration form page and the Confirmation page are in just the same page. What I did is that when the user submits the form, it will hide some elements including the Submit button and then just show the details he inputted. When the user clicks the Return button on the Confirmation page, it will just then show again the hidden fields so the user can edit his details.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working. I am using bootstrap for my form so when there are errors, the input fields' borders would turn red and would obtain a class has-error. Here's what I did:
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
But again, it is not working. I also googled some jQueries like the .valid() and .validate() functions but I'm not really sure about it and also didn't work for me.
I also did this code where the Submit button should disable when required fields are still empty. And it is perfectly working:
$('#submit').attr('disabled',true);
$('input[id^="account"]').keyup(function() {
if(($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0)) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
I hope you understand my problem. I will make it clearer if this confuses you.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working.
When is it checking for errors? It needs to disable the submit button at the same time it is checking for errors. Your code doesn't work because there's no event telling it WHEN to execute. WHEN do you want submit button to be disabled?
Do you want it triggered when the field is validated or when the form is submitted?
You can't really tie it to the submit button unless you want to click it first to validate the form fields, and then again to submit validated fields. Then you'll need to figure out how to tell it that it's been validated like by a class, maybe? Only accept inputs that hasClass('valid')?
below are the changes
$(".form-group").find("td").each(function() {
if($(this).hasClass('has-error')) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
Try the following
$('#submit').click(function(){
var error = false;
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
error = true;
return false; //break out of .each
}
});
return !error;
});
You can achieve this by maintaining 2 sections.
1. Form section
<form id="form1">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="button" id="confirm" value="Confirm" />
</form>
2. Confirm section
<div id="disp_data" style="display: none;">
<lable>Name: <span id="name_val"></span></lable>
<lable>Email: <span id="email_val"></span></lable>
<input type="button" id="return" value="Return" />
<input type="button" id="submit" value="Submit" />
</div>
You have to submit the form by using js submit method on validating the form in confirm section (When the user clicks on submit button)
$("#submit").click(function(){
var error_cnt = false;
if($("#name").val() == '') {
error_cnt = true;
alert("Enter Name");
}
if($("#email").val() == '') {
error_cnt = true;
alert("Enter Email");
}
if(error_cnt == false) {
$("#form1").submit();
} else {
$("#disp_data").hide();
$("#form1").show();
}
Demo
You have to prevent the form from sumition by return back a boolean false so that it will stop the execution.
$('#submit').click(function(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
if(!ret) return false;
});
If you want to disable the submit button in case of any error you need to monitor the changes of each input fields. so better to give a class name to all those input fields like commonClass
then
function validation_check(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
return ret;
}
$("#submit").prop("disabled",true)
$(".commonClass").change(function(){
if(validation_check()){
$("#submit").prop("disabled",false)
}
else {
$("#submit").prop("disabled",true)
}
});
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error. I've added fiddle you can try.
HTML FORM
<form action="" method="" onsubmit="return dosubmit();">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="submit" value="Submit" />
</form>
JAVASCRIPT
function dosubmit() {
if(false) { //Check for errors, if there are errors return false. This will prevent th form being submitted.
return false;
} else {
return true;
}
}
Let me know if this fixes your issue.

How to correctly validate form with jQuery?

So I have this jQuery for my form:
frm.submit(function(event) {
validateForm();
if(validateForm()) {
$(this).submit();
} else {
event.preventDefault();
}
});
It does sort of work, but I get JS <error> (and it doesn't say anything else in the console about it), I think the reason is that the function has to go through the validation again? Kind of like a circular dependency.
Can you show me a better way to do the exact thing that I'm trying to achieve here please?
Validate and show errors if filled in the wrong way;
Submit the form if everything is ok
Something like this maybe?
HTML -
<input type="text" id="name" />
<input type="tel" id="phone" />
<button type="button" id="submit">Submit</button>
<div id="errors"></div>
JS -
const user = {}
$('#submit').click(function(){
// validating form
if(!$('#name').val()) {
$('#errors').text('invalid value in "name" field')
return;
}
if(!$('#phone').val()) {
$('#errors').text('invalid value in "phone" field')
return;
}
$('#errors').text('');
user.phone = $('#phone').val();
user.name = $('#name').val();
// form submission goes here
});
Logic -
Once a function returns, the execution of anything else after the return expression itself, is prevented.
If you don't return anything, the interpreter will continue to the next expression.
This gives you the option of manipulating elements and handle errors just before returning and stopping the function from continuing to run.
function validateForm(){
if (input.val().isok && select.val().ispresent){
form.submit();
}else{
show_errors();
}
}
why not that way?

HTML5 form validation without submit button

i want to validate the form inputs without an type="submit" button.
How can i do this?
I tried this ->
<script type="text/javascript">function validateForm() {
$('#form1')[0].checkValidity()
if( document.form1.vorname.value == "" )
{
return false;
}
if( document.form1.nachname.value == "" )
{
return false;
}
if( document.form1.postleitzahl.value == "" )
{
return false;
}
if( document.form1.email.value == "" )
{
return false;
}
if( document.form1.telefon_optin_Ja.value == "" )
{
return false;
}
if( document.form1.ort.value == "" )
{
return false;
}
if( document.form1.straße.value == "" )
{
return false;
}
if( document.form1.Anrede.value == "" )
{
return false;
}else {
$('#modal_absenden').modal({
backdrop: 'static',
keyboard: 'false',
})
}
}
</script>
My form name is: form1 , button -> `Absenden
The "background" of the question is: I want to validate the form inputs first, then (if all inputs ok) it should opens a modal, where u can select the redirect page (redirect yes, redirect no) then it submit the form via post to mail.php.
I hope u understand my question, if u have questions, pls ask. (My english is not so good..)
Thank you for help.
You have said about HTML5.
Then that means all you have to do is to use checkValidity() along with
<input type="text" name="name" required>
<input type="email" name="email" required placeholder="Enter a valid email address">
Here is the nice article about using HTML5 validation.
I have not used by myself. But I am glad to know a bit from your post.
http://www.the-art-of-web.com/html/html5-form-validation/
If you want to use jQuery one then go for validation.
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You could call your validate function everytime an input changes:
$('#form1 input').change(validateForm);
Using
$("#form1 input").on('change,blur', validateForm);
function validateForm() {
// Caution : this refers to the HTMLElement
}
You shoud consider to use a jQuery form validation like library like http://formvalidator.net/ or http://jqueryvalidation.org/ or create yours.
Cheers
So I guess you want to do frontend validation with Javascript. There are wrapped library to do this. E.g., validate.js, verifyjs, and this one, ...
And you can bind the validation process on the blur event of an input
JQuery validate is a good choice with clear documentation. You just need to download the .js library and place it somewhere under your web folder, and using tag to include it. And call the .validate() function on the form you want to validate. That should be done.
$('input').on('blur', function(){
$("#myForm").validate();
});

Correct syntax for IF statement

Can anyone tell me why this IF statement doesn't work, please? I'm using jQuery and Firebug but the latter is not giving me any useful information.
I'm simply attempting to reveal a "submit" button when all of the fields have been completed and the script runs every couple of seconds to check for input.
My code excerpt goes a little like this:
function checkForm(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
// The following line shows me that the values for the fields are all getting picked up properly
$('#report').html("userName: "+userName+"<br />userContent: "+userContent+"<br />userEmail: "+userEmail);
// But the following line is throwing some kind of error
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideDown();
} else {
$('#update').slideUp();
}
}
$(document).ready(function(){
$('#update').hide();
setInterval('checkForm()' , 2000);
});
And my HTML...
<div id="report"></div>
<form id="submitfact">
<div id="update">Update Database</div>
<label><input id="name" name="name" type="text" value="" /><span>Fact submitter's name</span></label>
<label><input id="email" name="email" type="text" value="" /><span>Fact submitter e-mail address</span></label>
<label class="content"><span>Fact text</span><br /><textarea id="content" name="content"></textarea></label>
</form>
Edit...
I apologise if people think I'm wasting their time by not providing the error message - but Firebug simply isn't giving me anything useful - if it was I'd be posting it here. I am a reasonably experienced php programmer but fairly new to jQuery so I admit I am still getting to grips with both writing the language and debugging it. I'd like to post a screen shot of Firebug's response but, as a new user, I am not allowed... all I am getting is a "red error circle/yellow play triangle" icon in the line numbers column ("script" tab) on the line I've shown above... there is nothing else unless you can tell me where else to look other than the "script" and "console" panels?
Another edit...
Well, I got it fixed by taking a look at Cristoph's suggestion. It's basically the same solution but instead of calling it as a function I put it "inline". I'm not entirely sure what the difference between the two techniques is or whether it's simply a local issue I was having but my new jQuery looks like this:
$(document).ready(function(){
$('#submitfact').keyup(function(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
$('#report').html(userName + "<br />" + userContent + "<br />" + userEmail);
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideUp();
} else {
$('#update').slideDown();
}
});
});
I will have a look through your other comments to see if I can streamline it at all but at least I have a working baseline now! Thanks for your time, everyone :)
First of all, is it really throwing an error, or is it simply not working?
From how i understand your code, your if condition should be:
if (!userName === "" && !userContent === "" && !userEmail === ""){
// show
$('#update').slideDown();
} else {
// hide
$('#update').slideUp();
}
Second: doing this with a timer is a bad idea.
Introducing an eventhandler to check once an inputvalue changed is far better:
$("input").change(function(){
// if all inputs are filled, show Button, else hide it
});
P.S.
advanced insight into Javascript: an empty string is considered "falsy", thus
username === "" could be written as !username. Note however, that undefined, null, false, 0 and NaNare also considered "falsy"! THis means, you can't distinguish them. For this reason i prefer username === "" ( note the === ! )
Try changing your evaluation to this:
if (!userName || !userContent || !userEmail){
$('#update').slideDown();
} else {
$('#update').slideUp();
}

Categories

Resources