Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I usually code in Java, but I knew a little HTML, so I decided I would learn more. My problem is that I have a password field and a submit button. When I hit the button, it checks to see if the password is right, and then asks you what your name is. It then changes a text field to say You got it right, NAME. The thing is, when you hit submit, the code submitted is added to the URL, so if you type password as the password, ?password is added on to the URL. That is fine with me, but since the URL is changed, the page reloads, making the text field go back to normal. I am using Google Chrome. Is there anyway around this, or is it because I am running a .HTML file, not going to a website?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Ryan Club Homepage</title>
<script>
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
}
</script>
</head>
<body style="font-family:'Myriad Pro' ">
<form onsubmit="codeEnter();">
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!">
</form>
</body>
</html>
Thank you!
You need to use JavaScript / jQuery to prevent the form from submitting. I am using jQuery 2.1.1.
For password field let's assume it 123 for now.
The e.preventDefault() method stops the default action of an element from happening. Here it stops the submit button to submit the form to URL specified in form's action attribute.
$(document).ready(function(){
$("#name_container").hide();
$('#submit').on("click",function(e){
e.preventDefault();
$password = $('#password').val();
if($password == '123'){
$("#password_container").hide();
$("#name_container").show();
$("#result").html("");
}
else{
$("#result").html("Password is incorrect.");
}
$name = $("#name").val();
if($name != '' && $name != null ){
$("#form").hide();
$("#result").html("You got it right, "+$name);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" method="post" id="form">
<div id="password_container">
Password: <input type="password" id="password" />
</div>
<div id="name_container">
Name: <input type="text" id="name" />
</div>
<input type="submit" id="submit">
</form>
<div id="result">
</div>
(Updated)
Here you go:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="font-family:'Myriad Pro' ">
<form id="form" method="post" action="#">
Password:
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!" id="submit">
</form>
<div class="ps"></div>
<script>
$(document).ready(function () {
$('#submit').on("click", function (e) {
e.preventDefault();
$password = $('#in').val();
if ($password == 'lolliPiper5') {
$name = prompt("Enter your name", "ACCESS GRANTED");
$(".ps").html("Welcome to the team, " + $name);
}
});
});
</script>
</body>
</html>
In your simplified (I hope) code you need at least set
<form onsubmit="return codeEnter()">
...
// and in the script
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
else return false; //do not submit
}
In the real world if you actually wanted to submit the password, hidden from the user you would change the form code to
<form onsubmit="codeEnter();" method="post">
By default the form submits data to the server via a GET request which causes the values to show in the url, thus this is usually only used for making queries such as page numbers (?page=num) etc (all insensitive data).
However, when you set method="post" the form sends data using a POST request which is invisible to the user and in some cases encrypted before sending and therefore much safer.
An example of a for using method="POST" can be found here
Related
It is recommended to apply the code to the header from my own research. I checked my college lecture notes and I could not find how to represent my JS file externally. The filename is login.js which is in a folder called js.
HTML code ----------------------------------------->
`<!doctype html> <!-- This is a boostrap CDN template Bootstrap 4.6 version -->
<html lang="en">
<head>
<title>SportZone</title>
<script type="text/javascript" src="js/login.js">
</head>
<body>
<div>
<a class="active" href="#home">Home</a>
News
Contact
About
</div>
<div class="container">
<div class="main">
<h2>Javascript Login Form Validation</h2>
<form id="form_id" method="post" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username"/>
<label>Password :</label>
<input type="password" name="password" id="password"/>
<input type="button" value="Login" id="submit" onclick="validate()"/>
</form>
<span><b class="note">Note : </b>use the following username and password. <br/><b class="valid">User Name : user#gmit<br/>Password : pass</b></span>
</div>
</div>
</body>
</html>`
Javascript code------------------------------------>
`<!doctype html>
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
//type="text/javascript"
<script type="text/javascript" src="login.js">
var attempt = 3;
function validate(){
// Variable to count number of attempts.
// Below function Executes on click of login button.
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "user#gmit.ie" && password == "pass"){
alert ("Login successfully");
return false;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
</script>
`
Your browser tries to parse the content of your Javascript file, but since it's invalid as a Javascript code, will fail to do so.
Proof-of-concept
(Temporarily) remove EVERYTHING from js/login.js and put in there the following line:
alert("I'm a robot from the future! Beep! Beep!");
Load your HTML page. Do you see the alert dialog? If yes, go to the next section. If not, work, until you see it. What do you see in the Dev Tools Console? Do you see an error? If yes, then that error might be telling you that the file was not found. In that case check the access rights of the file and the location it is assumed to be at vs. its actual location.
The real thing
Now that you are able to write Javascript code into your file and that's executed, let's put in your real code into that file
var attempt = 3;
function validate(){
// Variable to count number of attempts.
// Below function Executes on click of login button.
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if ( username == "user#gmit.ie" && password == "pass"){
alert ("Login successfully");
return false;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
It appears that you've mixed HTML into your Javacript file. Simply remove all of the HTML, including the <script> tag, from your login.js file. JS files should only contain JS.
Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.
I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}
I have a really weird error in my code that I just cannot figure it out. Basically, I'm making a simple username save/recall form. I take in input from a user and save it into a localstorage of browser. After, when I try to access with the input from before, I would recall the item from the localstorage.
My if statement doesn't seem to work. I tried comparing items individually - I tried comparing "document.getElementById('userName')" with a random string and "localStorage.getItem('login_info')" vice versa. However, when I try to do
if (localStorage.getItem('login_info') === document.getElementById('userName'))
The code would never return true as an output.
any ideas?
Thanks!
<!DOCTYPE html>
<html>
<head>
<title>Try</title>
</head>
<body>
<p> Please type in your username and password </p>
<form id="register_form">
<input id="name1" type="text" placeholder="Name" value=""/>
<input id="rgstr_btn" type="submit" value="Register" onClick="store()"/>
</form>
<form name="login">
<input id="userName" type="text" placeholder="Enter Username" value=""/>
<input id="login_btn" type="submit" value="Login" onClick="check()"/>
<input type="reset" value="Cancel"/>
</form>
<script type="text/javascript">
var user_name = document.getElementById('name1');
function store(){
localStorage.setItem('login_info', user_name.value)
}
function check(){
var storedName = localStorage.getItem('login_info');
// entered data from the login form
var user_Name = document.getElementById('userName');
if (document.getElementById('userName') === localStorage.getItem('login_info')){
alert("Login Successful! Continuing to ..");
window.open("Us.html");
}
else{
alert("Login unsuccessful, please try again!");
}
}
</script>
<noscript> Please try a different browser! </noscript>
</body>
</html>
Use document.getElementById('userName').value to fetch value from input text.
var user_name = document.getElementById('name1');
function store(){
localStorage.setItem('login_info', user_name.value)
}
function check(){
var storedName = localStorage.getItem('login_info');
// entered data from the login form
var user_Name = document.getElementById('userName').value;
if (document.getElementById('userName').value == localStorage.getItem('login_info')){
alert("Login Successful! Continuing to ..");
window.open("Us.html");
}
else{
alert("Login unsuccessful, please try again!");
}
}
Like #DhavalSoni said, you need to use element.value to compare.
document.getElementById is only meant to return the DOM object and not its value. Try console.log(Document.getElementById('username')) to examine the returned object in Chrome debugger.
i got the problem with validation in my form. Validation actualy works in every explorer, but how is it possible to receiving an empty form in my mail box. I dont understand..thanks for any help!
<script>
function kontrolaDat(myForm){
if (window.RegExp)
{
znaky=new RegExp("^[^.]+(\.[^.]+)*#([^.]+[.])+[a-z]{2,3}$");
if (!znaky.test(myForm.email.value))
{
window.alert("Zadaný e-mail nie je platný!");
return false;
}
}
if(myForm.jmeno.value == "") {
alert("Zadajte prosím svoje meno");
return false;
}
if(myForm.telefon.value == "") {
alert("Zadajte prosím váš telefón");
return false;
}
if(myForm.psc.value == "") {
alert("Zadajte prosím vaše PSČ");
return false;
}
else return true;
}
</script>
<div class="span4 text">
<h4>Najlepšiu hypotéku aj vám!</h4>
<p>Žiadne poplatky - Žiadne záväzky - Skvelý servis<br />Vyplňte formulár a my vás budeme kontaktovať.</p>
<form method="post" action="hypoteka-dakujeme.php" onsubmit="return kontrolaDat(this);">
<input type="text" name="email" placeholder="Emailová adresa" />
<input type="text" name="jmeno" placeholder="Vaše meno" />
<input type="text" name="telefon" placeholder="Kontaktný telefón" />
<input type="text" name="psc" placeholder="PSČ" />
<input type="submit" name="submit" value="Chcem najlepšiu hypotéku!" class="btn tlacitko" />
</form>
</div> <!-- End text -->
If you disable JavaScript no validation is done. Validate the form on the server side - in hypoteka-dakujeme.php before sending the email. You should never use client side validation only - it can be easily bypassed.
Please rephrase your question, you say in the title that the alerts in the form does not work, but then you say that the validation via JavaScript is working properly and the problem is that you get the email with no data.
So if the JavaScript works as expected .. focuses attention on the PHP that receives and processes the data sent.
I would start by adding the following code at the top of the file hypoteka-dakujeme.php
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
...then, you must debug the code to print on screen (for example) the information you expect to receive in the email.
If you get the information you expect, then send the email. If you still get an empty email... check the mail() function that you are using.
If need more help, please rephrase the question including relevant information.
Good luck any way.