Javascript: Enter does not work for submitting password - javascript

I can't get the following code working: when I press enter in the text-box, the function is not called. I can't see why though...
<form>
<p align="center">
<input type="password" class="password" name="text1" onkeypress="submitonenter(text1.value,"money","cash",event)" /><br>
<input type="button" value="Enter" style="width: 100px" name="Enter" onclick=javascript:validate(text1.value,"money","cash") />
</p>
</form>
<script type="text/javascript">
function submitonenter(text1,text2,text3,evt) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
if (text1==text2)
load('money/welcome.html');
else
{
if (text1==text3)
load('cash/welcome.html');
else
{
load('failure.html');
}
}
}
}
}
</script>
<script language = "javascript">
function validate(text1,text2,text3)
{
if (text1==text2)
load('money/welcome.html');
else
{
if (text1==text3)
load('cash/welcome.html');
else
{
load('failure.html');
}
}
}
function load(url)
{
location.href=url;
}
</script>

I'm not sure why you need the submitOnEnter function at all.
Why not just change the input type='button' to type='submit' and change the onclick keyword to onsubmit?
EDIT:
Apologies, of course the 'onsubmit' would need to be placed in the form tags, not the input.
Giving the following:
<form onsubmit=validate(text1.value,"money","cash") >
<p align="center">
<input type="password" class="password" name="text1" /><br>
<input type="submit" value="Enter" style="width: 100px" name="Enter" />
</p>
</form>

I would rewrite it all, and use a input type="submit" instead a button (I also changed the access to the password field, for being able to use it at Firefox):
<form id="myForm" method="POST" action="failure.html" onsubmit="return validate(document.getElementById('text1').value,'money','cash');">
<p align="center">
<input type="password" class="password" name="text1" id="text1"/><br>
<input type="submit" value="Enter" style="width: 100px" name="Enter" />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3) {
var form=document.getElementById('myForm');
if (text1==text2)
form.action='money/welcome.html';
else {
if (text1==text3)
form.action='cash/welcome.html';
else {
form.action='failure.html';
}
}
return true;
}
</script>
Edited: Implementing the onSubmit as recommended by #mway (thanks).

Like the others said - remove the onclick event, change the button to a submit button, and put the rest of your code inside a function referenced by an onsubmit tag on the form if you need to process/reformat data before you submit it.

After you have confirmed that the enter key has been pressed you want to call "evt.preventDefault()" to prevent the default action (ie form submission) from happening. I believe what is happening is that you are setting the location.href but then the form is submitting before that load happens so it reloads the same page instead.
Others have mentioned server side processing and from a security point of view this is probably a good idea. Currently this page has no security whatsoever. Anybody can look at your javascript and choose to navigate to either of the two welcome pages (or the failure page) as if they had put in the password correctly. If this is meant to be secure then you might want to go and read articles about security. In summary though do password checks and following logic on the server and don't have passwords that are that easy to guess. :) Also you might want to include checking they have given the correct password on every page (eg the welcome pages). This can easily be done by setting a session variable once you have confirmed their password.

Related

How do i make a js code that redirects to a certain html page with a certain input?

let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>

Multiple form validation with same function

I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})

Is it possible to execute simple javascript statments from an input field in a document?

In the example below I've attached a function main to an input field. the function contains instructions to send an alert with a variable message (whatever the user enters into the field).
<form>
<input type="text" onsubmit="main()" />
<input type="submit" />
</form>
<script>
function main (param) {
alert(param)
}
//main();
</script>
It doesn't work, but I believe that's because I've made some noob error that I'm failing to recognize. The result of a functioning version of this code would be the ability to submit "hello world" and produce an alert box stating 'hello world' (without quotes).
But, further than this, I'd like to be able to pass the likes of main("hello world"); or just alert('hello world'); to the input field to produce the same result.
The problem I think I'm running into is that the page is refreshed every time I submit. There are a few questions on here with similar problems where people have suggested the use of onsubmit="main(); return false;", but in fact this does not seem to work.
Looks like you want to eval() the value of the input.
Use with caution, has security impact...
Returning false from a handler stops the regular action so you have no redirect after submitting:
<form onsubmit="main(); return false;">
<input id="eval-input" type="text" />
<input type="submit" />
</form>
<script>
function main () {
eval(document.getElementById('eval-input').value);
}
</script>
Here's how you can detect a form submission:
<form onsubmit="foo()">
<input type="text">
<input type="submit">
</form>
<script>
function foo(){
alert("function called");
}
</script>
I however advise you do this (preference), if you desire to manage the form data through a function:
<form id="myform">
<input type="text">
<input type="submit">
</form>
<script>
document.getElementById("myform").onsubmit=function(event){
alert("function called");
//manage form submission here, such as AJAX and validation
event.preventDefault(); //prevents a normal/double submission
return false; //also prevents normal/double a double submission
};
</script>
EDIT:
use eval() to execute a string as JavaScript.
jQuery way:
You create event listener which will be triggered when user click 'submit'.
<form>
<input type="text" id="text"/>
<input type="submit" />
</form>
<script>
$( "form" ).submit(function( event ) {
event.preventDefault();
alert( $('#text').val() );
});
</script>
To prevent page reloading - you should use event.preventDefault();
Pure JavaScript:
<form>
<input type="text" id="text"/>
<input type="submit" id="submit" />
</form>
<script>
var button = document.getElementById("submit");
var text = document.getElementById("text");
button.addEventListener("click",function(e){
alert(text.value);
},false);
</script>
If I understand what you want to do, you can call the function like this, and writing params[0].value you can access the input value:
function main(params) {
//dosomething;
document.write(params[0].value);
}
<form onsubmit="main(this)">
<input type="text">
<input type="submit">
</form>
Try something like this
onchange="main()"
onmouseenter, onMouseOver, onmouseleave ...
<input type="text" onmouseenter="main()" />

When I press enter key, unable to login

I have been trying to log in to a offline HTML/CSS page using the enter key but unable to start with JavaScript which needs I'm sure.
But can log in using the mouse when I click the log in button which i have created ..
How do i use the enter key stroke to log in?
This is the javascript which I have hard coded for credential test which works using the mouse click.. I want it for the enter key.. Thank you.
<!DOCTYPE HTML>
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<div align="center">
<div id="bor">
<h1>
Login Page
</h1>
<div>
<form name="login">
&nbsp<input type="text" placeholder="Enter the Username" name="user"/> <br />
<input type="password" placeholder="Enter the Password" name="pwd"/><br /><br />
<input type="checkbox" name="en" value="en" />Remember Me<br>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</div>
<script language="javascript">
function check(form)
{
if(form.user.value == "user" && form.pwd.value == "pwd")
{
window.open('inbox.html','_self')
}
else
{
alert("Error Password or Username")
}
}
</script>
Use the submit event handler. The click handler on an element will only fire if you click on it. What you are trying to do is submitting a form, but handling the form with javascript instead of on the server. I would recommend binding that dynamically, but as you have all javascript here inline, I'll give an example inline too.
You'll need to attach a submit event handler to the form element. If you do it inline, this will work with onsubmit="..." instead. The return is there to prevent/allow the form to be submitted to the server. If the function returns 'true', the form will be submitted to the server. If the function returns 'false', the form will not be submitted. You'll also need to change the type of your submit button to submit. This will tell the browser to submit the form if that button is clicked. Alternatively, if you press enter in an input field, the browser will see this as submitting the form too.
<form name="login" onsubmit="return check(this)">
&nbsp<input type="text" placeholder="Enter the Username" name="user"/> <br />
<input type="password" placeholder="Enter the Password" name="pwd"/><br/><br/>
<input type="checkbox" name="en" value="en" />Remember Me<br>
<input type="submit" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
The javascript behind it will remain mostly the same. You'll notice that we passed this to the function. This will pass the element itself (in this case the form element) to the function. As said before, you'll need to return false. I've changed form to frm as form is a globally defined variable in some browsers.
function check(frm)
{
if(frm.user.value == "user" && frm.pwd.value == "pwd")
{
window.open('inbox.html','_self')
}
else
{
alert("Error Password or Username")
}
return false;
}
An example jsfiddle: http://jsfiddle.net/AS5t5/

Validate that a URL entered in a form is from a specific website with javascript

I have a website where people post links from Google+. I am trying to make sure that people can only post specific links from Google plus. An example would be, someone would need to post a link like
https://plus.google.com/games/907809777960/params/%22%7B%5C%22encPrms%5C%22%3A%5C%22eyJiYXBpVGlja2V0SWQiOiI4MzFhNGQ0Ny0yYTU4LTQ2OTktYmI1Yy1hN2ExYTAzY2U4ZTMiLCJsYW5kaW5nUGFnZSI6Im5ld3NmZWVkL2JvbnVzYWJsZUZlZWQvbWFydmVsY29tcGxldGUvNTQ3Mjc3LzEzMTQ0NzA0MjUvMCIsInJlZl9pZCI6IjEwOTkyODAzNzUzNzQ2Mjk5NzAxMCIsInRyYWNrIjoibmV3c2ZlZWQtYm9udXNfbWFydmVsQ29tcGxldGUtMCIsInNlbmRfdGltZXN0YW1wIjoiMTMxNDQ3MDQyNyJ9%5C%22%7D%22/source/3.
I want to make sure that the link starts with or at least contains https://plus.google.com/games/907809777960/params/, if not, it will not submit the link and alert that the link is invalid. The code I have so far is.
<script type="text/javascript" language="JavaScript">
function checkForm(theForm) {
if (form.bonuslink.indexOf("https://plus.google.com/games/907809777960/params/") == -1)
{ alert('You can only enter authentic Google + links'); return false; }
else {
return true; }
}
</script>
<form action="submitbonus.php" onsubmit="return checkForm(this);" method="post">
Bonus Link: <input name="bonuslink" type="text" size="40" /> <input name="Submit" type="submit" value="Submit Bonus" /><br />
</form>
I cannot get it to work for some reason. It submits every time regardless of what it typed. I am not that familiar with javascript, so any help would be appreciated.
edit edit: you have two problems you need to reference the bonuslink value not the DOM element itself and you need to call it as a member of the 'theForm' instead of 'form' since that is what you called the parameter. Other than that everything should be fine.
<script type="text/javascript" language="JavaScript">
function checkForm(theForm) {
if (theForm.bonuslink.value.indexOf("https://plus.google.com/games/907809777960/params/") == -1){
alert('You can only enter authentic Google + links');
return false;
} else {
return true;
}
}
</script>
<form action="submitbonus.php" onsubmit="return checkForm(this);" method="post">
Bonus Link: <input name="bonuslink" type="text" size="40" /> <input name="Submit" type="submit" value="Submit Bonus" /><br />
</form>
this regular expression will extract the domain name from any string.
basically it'll return the part starting from http:// etc.
/((https?|s?ftp|dict|www)(://)?)[A-Za-z0-9.\-]+)/gi
it'll detect the following forms:
http://www.google.com
https://www.google.com
ftp://www.google.com
dict://www.google.com
www.google.com
enjoy.

Categories

Resources