I am having a little problem here for some reason. I have another page with almost the exact same code and it redirects the user to the page that I want them to go to. For some reason this one does not. I have tried commenting out the if statement and everything down to the point of just having the window.location.replace with the click action and still no luck.
JS
$(document).ready(() => {
$("#login-button").click(() =>{
if($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.replace('../index.html');
} else {
alert("You have the wrong password and username");
}
});
});
HTML
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
You're mistaking what location.replace() is used for. To redirect, use location.href instead.
window.location.href = '../index.html';
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
You also need to prevent the form submit. This is causing the page to be posted back to itself. Add the following inside your form submit event handler.
e.preventDefault();
You just need to stop the default form submit
html
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
jQuery
$(function() {
$("#login-button").click((e) {
if ($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.href('../index.html');
e.preventDefault();
} else {
alert("You have the wrong password and username");
e.preventDefault();
}
});
});
Related
I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!
This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is
<button type="submit" id="btn" onclick="validate()">login</button>
However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
HTML
<div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
JS
//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not
function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem
Firstly its not
document.getElementById('password');
value;
its
document.getElementById('password').value;
Secondly, there is no action property present I'll suggest removing the entire form tags
<div class="wrapper">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type=" submit" id="btn" onclick="validate()">login</button>
</div>
<script>
function validate() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
if (username == 'please' && password == 'work') {
alert('finally');
} else {
alert("NOOOO")
}
}
</script>
on your for, you are using attibute method="post" which has alternative of method="get" which being sent using URLs you are using method="post" which has a missing attribute action="/action_page.php" that will process you're page.
Like this
<form class="box" action="/action_page.php" method="post">
since you don't have action attribute, and has method="post", the post is being sent to the same page you are sending and without receiving it properly like in php.
$username = $_POST['username'];
If you still want to continue using javascript at test it, remove at post method, and remove the type="submit" on your button as it behaves on submitting if you just want to test using javascript.
Here is your final script.
HTML
<form class="box">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button id="btn" onclick="validate()">login</button>
</form>
</div>
JS
function validate(){
let username = document.getElementById('username').value;
let password=document.getElementById('password').value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have a form to submit several fields. Two of them are for changing a password.
These password fields aren't required to be filled out before submitting. However, if one of them isn't blank I add the required attribute to both fields when it's changed through jQuery. I remove the attributes when I empty one and the other is already empty too.
The thing it seems to work the most of the times with an exception:
I fill out password
password2 is blank
I submit the form
In this case the validation for password2 shows up, but if I want to remove everything and submit, I can't:
I remove password
I submit the form again
The validation for password2 shows up again. Even if the 'required' attributed is removed in the HTML source
This is the HTML code:
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
And the jQuery code:
$('#password').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$( '#password2' ).attr('required', true);
}else{
if($('#password2').val() == ''){
$(this).removeAttr('required');
$( '#password2' ).removeAttr('required');
}
}
});
$('#password2').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$('#password').attr('required', true);
}else{
if($('#password').val() == ''){
$(this).removeAttr('required');
$('#password').removeAttr('required');
}
}
});
And it's an example in JSFiddle:
https://jsfiddle.net/jke3pgh0/
I will suggest you a different approach here...
First, you only need one handler for this, since the logic is the same for both inputs. You can use more than one selector... Ex: $('#password, #password2'). But I would use a class instead... Like $(".password"). It's up to you.
Second, I said the «logic is the same»... That is:
If one of the two inputs is not empty, both are required.
So having the same change event handler on both inputs mean you don't really know which one triggered the event. So I suggest to use an .each() loop here (to make sure you check all values)... and a boolean "flag" (true/false).
After that loop, use that "flag" to set the required attribute.
I used a CSS rule to make the result obvious in the snippet below.
$('#password, #password2').change(function(){
// Look up for the password inputs in that "row".
var pass_inputs = $(this).closest(".row").find("[type='password']");
// Flag to determine if at least one is not empty.
var not_empty = false;
// Loop throug the password inputs and change the flag.
pass_inputs.each(function(){
if($(this).val() != ''){
not_empty = true
}
});
// Use the flag as the boolean argument for the required attribute.
pass_inputs.attr('required', not_empty);
});
[required]{
border: 3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
This is my first post so don't judge me if i do something wrong because i'm still learning but i have a question i'm making a form and i have a problem. When i left the button without any extra stuff when i tested the form i got as many entries as many times i clicked the button so i used a code snippet from here in JS and made the button so it disappears, problem is when i don't fill the form correctly it doesn't send the entry, so the question is how can i add the condition in form so the button only disappears when every field is written correctly? I would add the whole html but it's houndreds of lines of code now since it's pretty much where i test things here is the form code though.
My other thought was to maybe try to edit the php code, but to be honest i have no knowledge of that because my friend made that.
I also searched google and here for some tips but couldn't find any, thanks for help in advance.
$("#hideme").click(function(){
$(this).hide();
});
<form method="post" action="thankyou.php" style="overflow:hidden" class="accident-form4">
<input type="hidden" name="lang" value="pl">
<div class="form-group required">
<label for="name">Imię i nazwisko<span></span></label>
<input type="text" class="form-control inputToUpper" name="firstname" placeholder="Andrzej Kowalski" required="required" pattern=".*\S+.*" title="Wpisz swoje imię">
</div>
<div class="form-group required">
<label for="email">Email<span></span></label>
<input type="email" class="form-control" required="required" name="email" placeholder="np. andrzej.kowalski#gmail.com" title="Wpisz poprawny adres email!" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="form-group">
<label for="tel">Numer telefonu<span></span></label>
<input type="text" name="tel" placeholder="079 1234 5678" class="form-control" required="required" size="12" value="">
</div>
<label for="hour">Preferowana godzina kontaktu</label>
<select class="form-control" name="hour" placeholder="" title="" />
<option>Dowolna</option>
<option>Rano</option>
<option>Po południu</option>
<option>Wieczorem</option>
</select>
<input type="submit" name="lead" class="send" id="hideme" value="ROZPOCZNIJ CLAIM →">
</form>
you can simply check the value of the required fields before hiding the button.
$("#hideme").click(function(){
if (document.getElementsByName('firstname')[0].value != '' &&
document.getElementsByName('email')[0].value != '' &&
document.getElementsByName('tel')[0].value != '') {
$(this).hide();
}
});
or use your RegExp in Javascript again.
$("#hideme").click(function(){
if (document.getElementsByName('firstname')[0].value.match (/.*\S+.*/) &&
document.getElementsByName('email')[0].value.match (/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$/) &&
document.getElementsByName('tel')[0].value.match (/[0-9]+/)) {
$(this).hide();
}
});
that should to the trick (but i didn't test it).
i'm working with the forms and i want when i hit the submit buttom only that field gets red which are empty . don't knw how to fix it . if anyone can help me i'm new javascript and jquery thanks
My HTML
<form id="form">
<div class="form-group">
<label>Username</label>
<p><span id="usernameError"></span></p>
<input type="text" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label>Email</label>
<p><span id="emailError"></span></p>
<input type="email" class="form-control" id="email" placeholder="email">
</div>
<div class="form-group">
<label>Password</label>
<p><span id="passwordError"></span></p>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<p><span id="confPasswordError"></span></p>
<input type="password" class="form-control" id="confPassword" placeholder="Confirm Password">
</div>
<p><span id="warning"></span></p>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
MY JAVASRIPT
now here is the situation . i put all the variables in one if statement and that's why they all are turning into red
$("#form").submit(function(){
if(password.val() != confPassword.val() )
{
alert("password dont match");
}
if($(this).val() == ""){
username.addClass("border");
email.addClass("border");
password.addClass("border");
confPassword.addClass("border");
// warning message
message.text("PLEASE FILL OUT ALL THE FIELDS").addClass("boldred");
// errors rendering
usernameError.text("username must be defined").addClass("red");
emailError.text("email must be valid and defined").addClass("red");
passwordError.text("password must be defined").addClass("red");
confPasswordError.text("confirm password must be matched and defined").addClass("red");
// disabling submit button
submit.attr("disabled" , "disabled");
return false;
}
else{
return true;
}
});
Try JQuery Validation Engine. Its very easy to implement your form.
Validation Engine
Supported for all browsers
First try adding required to all the necessary fields, like:
<input type="text" class="form-control" id="username" placeholder="Username" required>
Then disable (or delete) the if clause.
If that doesn't work, just let me know in the comments and I'll update the answer.
You are approaching the problem in incorrect way.
On Form submit you need to check each field you want separately.
For example:
$("#form").on('submit', function() {
var submit = true;
$(this).find('span').removeClass('red');
$(this).find('input').each(function() {
if ($.trim($(this).val()) === '') {
submit = false;
$(this).parents('.form-group').find('span').addClass('red');
}
});
return submit;
});
I have a little form in my modal which looks like this:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="edited_email" class="form-control" id="edit_email" value="">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
and I want to prevent the form to submit if the user enters an email that it is already in my database. I have the following script:
$("#check_email").click(function() {
var email = $(this).parent().siblings().find("#email").val();
var that = $(this);
$(this).parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
});
});
The problem is that if I put the even.preventDefault() in that else condition, the $.get() seems to not trigger, because I guess that the form submits faster. Otherwise if I put the event.preventDefault() right after the .submit(function( event ) { then I can't unbind the submit to work after the user changes the email.
What I am doing wrong?
P.S.
My php file looks like this:
<?php
include "connect.php";
if(isset($_GET['email']) && !empty($_GET['email'])){
$sql = "SELECT * FROM users WHERE email='".$_GET['email']."';";
$result = $conn->query($sql);
if ($result->num_rows > 0){
echo "The email is already in our database. Please try another one!";
}
}
?>
I understand you would like to avoid form sending if email is already used.
At first, where is your magic button to do this :D ?
I added button in example.
You must be sure that your "this" is element you want, creating structure like .parent().parent().parent() everywhere is stupid - one change and everything not work.
Next thing to avoid form submit you must return false; inside submit function, preventDefault() work with <a> or other events like click
And next.. if you send ajax your callback function can back to your browser after your submit click.
For example checkClick -> sendAjax -> submitClick -> ajaxBack
And next :D - PHP: Your form have method="post" but server use $_GET
So.. if you send post you must use $_POST if get than $_GET
This time you used $.get so i dont know your ajax configuration but this can cause errors.
Here is some code but im sure this is not final implementation you want, but it should help :)
sorry for english btw.
html:
<form name="form" action="" method="post">
<div class="modal-body">
<input type="text" name="edited_id" value="" id="edited_id" class="hidden"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="edited_name" class="form-control" id="edit_name" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="edited_email" class="form-control" id="edit_email" value=""> <button type="button" id="check_email" data-dismiss="modal">check</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="edit_submit" class="btn btn-primary" value="Edit user"/>
</div>
</form>
javascript:
$("#check_email").click(function() {
var email = $(this).parent().find("#email").val();
var that = $(this);
alert(email);
console.log($(this).parent().parent().parent())
$(this).parent().parent().parent().submit(function( event ) {
$.get("php/verify_email.php", {email: email}, function(data){
if(data === "")
{
that.parent().parent().unbind('submit').submit();
}
else {
alert(data);
event.preventDefault();
}
});
return false;
});
});