Using the Enter key to Access Submit Button in HTML - javascript

I have searched and applied almost every code I could get but nothing seems to work.
I am trying to implement validation and I just wanted that as soon as I press Enter on the Password field, it will access the submit button ALONG WITH the function being called..
Here is my entire (FAIRLY LONG :D ) code
<!DOCTYPE html>
<html>
<head>
<title>Student Information</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script>
function reset()
{
document.forms['testform'].reset();
document.getElementById("x1").focus();
}
function passfocus()
{
document.getElementById("x2").focus();
}
function passreset()
{
document.getElementById("x2").value="";
document.getElementById("x2").focus();
}
function Result()
{
var user=document.getElementById("x1").value;
var pass1=document.getElementById("x2").value;
passw=+pass1;
var at=user.indexOf("#");
var dot=user.lastIndexOf(".");
var sub=user.substring(user.length, dot+1);
for(i=0;i<sub.length;i++)
{
var d=sub.charAt(i);
if(d==='0' || d===',' || d==='?' ||d===';' || d===':' || d==='+' || d==='=' || d==='-' || d==='1' ||d==='2' || d==='!' ||d==='#' ||d==='#' ||d==='$' ||d==='%' ||d==='^' ||d==='&' ||d==='*'|| d==='(' || d===')'|| d==='3' ||d==='4' ||d==='5' ||d==='6' ||d==='7' ||d==='8' ||d==='9')
var d1=0;
else
var d1=1;
}
var count=0;
for(j=0;j<user.length;j++)
{
var d2=user.charAt(j);
if(d2=='#')
count=count+1;
}
var flag=0;
for(k=0; k<(user.length-1); k++)
{
if(user.charAt(k)==='.' && user.charAt(k+1)==='.')
flag=1;
}
if(!user)
{
alert("Field is mandatory");
}
else if(d1===0)
{
alert("E-mail not valid");
reset();
}
else if(count===2)
{
alert("E-mail not valid");
reset();
}
else if(at<1 || dot<at+2 || dot+2>=user.length)
{
alert("E-mail not valid");
reset();
}
else if (flag===1)
{
alert("E-mail not valid");
reset();
}
else
{
if(passw===0)
{
alert("Please enter password");
passfocus();
}
else if(pass1.length<8)
{
alert("Password must be greater than 8 characters");
passreset();
}
else
{
alert("you have successfully submitted the form");
reset();
}
}
}
</script>
</head>
<style>
p.serif{font-family:"Times New Roman",Times,serif;}
.sansserif{font-family:Arial,Helvetica,sans-serif;}
.td1{text-align:middle;}
table,td,th
{
border:1px solid red;
}
table
{
width:100%;
}
th
{
height:50px;
}
td
{
padding:15px;
}
</style>
<body style="background-color:AntiqueWhite;">
<h2 align="middle" style="background-color:White;"><font color="MediumVioletRed">Student Login</font></h2>
<p align="middle" class="sansserif" style="background-color:yellow;"><b><i><font color="Maroon">Enter Student Credentials below to login</font></i></b></p>
<table border="1" >
<th>CREDENTIALS</th>
<tr>
<td class="sansserif">
<form name="testform" align="middle"
<div style="color:#006400" class="myCustomDiv">
E- mail ID: <input type="text" name="usern" id="x1">
<br>
Password: <input type="password" name="pass" id="x2" >
<br>
<button type="button" onclick="Result()" align="middle" id="x3">Login</button>
</div>
</form>
</td>
</tr>
</table>
</body>
</html>
Just for detailing, I didn't shorten it. It is very basic I know, I'd be really thankful if anyone could help.

You have terrible errors in your html. There is a <style> element between the </head> and the <body>. Things like that are a no-no!
And the definition for the form is not complete: you are missing the > on the start tag, as well as the action attribute. The latter is mandatory and is the cause for the inability to submit.
Other than that, you have other errors, like in the javascript.
What does, for instance, passw=+pass1 mean?
But all those are secondary to the problems with the form start tag. Repair those first, then you can test properly, because submit will work.

Related

HTML check user input in form for letters

Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>

Can I Set Some HTML5 Validation With JQuery In A Certain Way?

So I have a textarea in my form that has a minlength="15" and maxlength="2000". But this means that when the user reaches 2000 characters, he can type no more. What I want is the user to have the ability to type ever more character, but use client-side validation, on submit, to check if the textarea value is valid. If not, I want to make it invalid, and show the default HTML5 validation bubble. Here is my code so far:
textarea {
min-height: 100px;
min-width: 250px;
}
#charLeft {
color: red;
}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="POST">
<textarea placeholder="Describe Your Issue*" aria-placeholder="Describe Your Issue" name="describeIssue" id="describeIssue" class="describeIssue" onkeyup="countChar(this)" minlength="15" maxlength="2000" required></textarea>
<div id="charLeft">0/15</div>
<br />
<input type="submit" />
</form>
<script type="text/javascript">
function countChar(val) {
let length = val.value.length;
if (length > 15 && length < 2000) {
$('#charLeft').html(length + '/2000');
$('#charLeft').css('color', '#27ae60');
} else if (length < 15) {
$('#charLeft').html(length + '/15');
$('#charLeft').css('color', '#e74c3c');
} else {
$('#charLeft').html(length + '/2000');
$('#charLeft').css('color', '#e74c3c');
}
}
</script>
</body>
As seen above, if you get to the limit of 2000 characters, the textarea won't allow any more. I want it that it will go past 2000 characters, but when you submit, and if it is past 2000 characters, mark it invalid. I am not sure how to do that, so that is where I would need some assistance. I can accept plain JavaScript or JQuery. Thanks in advance, and any help is appreciated!
In the HTML, remove the maxlength property. This will allow users to type more then 2000 characters. In the JS, add a submit handler that checks, like so:
function countChar(val) {
let length = val.value.length;
if (length > 15 && length < 2000) {
$('#charLeft').html(length + '/2000');
$('#charLeft').css('color', '#27ae60');
} else if (length < 15) {
$('#charLeft').html(length + '/15');
$('#charLeft').css('color', '#e74c3c');
} else {
$('#charLeft').html(length + '/2000');
$('#charLeft').css('color', '#e74c3c');
}
}
$("form").submit((e) => {
var val = $("#describeIssue").val();
if (parseInt(val.length) > 2000) {
e.preventDefault();
alert("To Long!");
} else {
//the user passed the lenghth
}
});
textarea {
min-height: 100px;
min-width: 250px;
}
#charLeft {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form action="" method="POST">
<textarea placeholder="Describe Your Issue*" aria-placeholder="Describe Your Issue" name="describeIssue" id="describeIssue" class="describeIssue" onkeyup="countChar(this)" minlength="15" required></textarea>
<div id="charLeft">0/15</div>
<br />
<input type="submit" />
</form>
This code allows the user to type more than 2000 characters, but they cannot submit the input if it has a problem (goes over the length).
You can allow the user to type more than 2000 characters and then return a custom error message, but you can't do that and show the default HTML5 error. To achieve the former, remove maxlength="2000" and add an onsubmit listener to the form, in which you will check whether the length of the text has exceeded 2000 characters, then decide to submit the form or not.
function countChar(val) {
let length = val.value.length;
if (length > 15 && length < 2000) {
$('#charLeft').html(length + '/2000');
$('#charLeft').css('color', '#27ae60');
} else if (length < 15) {
$('#charLeft').html(length + '/15');
$('#charLeft').css('color', '#e74c3c');
} else {
$('#charLeft').html(length + '/2000');
$('#charLeft').css('color', '#e74c3c');
}
}
$('#describeIssue').on('submit', function(event) {
if ($('#describeIssue').value.length > 2000) {
event.preventDefault();
}
});
textarea {
min-height: 100px;
min-width: 250px;
}
#charLeft {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
<textarea placeholder="Describe Your Issue*" aria-placeholder="Describe Your Issue" name="describeIssue" id="describeIssue" class="describeIssue" onkeyup="countChar(this)" minlength="15" required></textarea>
<div id="charLeft">0/15</div>
<br />
<input type="submit" />
</form>

Why this form is still submitting?

I am really tired of this form i was trying to prevent it from submitting for a time that i can not remember!
I am trying to prevent the form from submitting if the validation is not true, I believe that it's submitting when it is looking for file codes.txt
Please anyone tell me how can i submit it only after my validations are correct?
Help me stack overflow! you are my last hope.
$('form').submit(function() {
var errors = 0;
$("form input[required]").map(function(){
if( !$(this).val() ) {
errors++;
}
});
$("form textarea[required]").map(function(){
if( !$(this).val() ) {
errors++;
}
});
if(errors > 0){
alert("You must fill out the required fields");
return false;
}
if(!$('#terms-checkbox').is(':checked')) {
alert('You must accept the terms and conditions');
return false;
} else {
if ($.trim($('#code').val()).length == 0){
alert("You must enter code");
} else {
$.get('codes.txt', function (contents) {
if (contents.includes($('#code').val())) {
validForm =true;
} else {
alert("Sorry!! That is not a valid code.");
return false;
}
});
}
}
});
<script type="text/javascript">var validForm=false;</script>
<iframe name="hidden_iframe" id="hidden_iframe" style="display:none;" onload="if(validForm) {window.location='confirmation-page.html'}"></iframe>
<form action="https://docs.google.com/forms/d/e/1FAIpQLSdC9Jr65fCIhRLiSXzVRoDKJAB8was3LoyN0DaCVrVLRa-nJg/formResponse" target="hidden_iframe" method="post">
<!--Some Inputs goes here-->
<input id="terms-checkbox" type="checkbox" name="aaaa" value="Bike"> <span style="color: red;font-size: 14px;">*</span> I have read and agree to the above terms and conditions
<input type="submit" value="Send" class="form-control btn-default" >
</form>

Add CSS when there's an error

I have a simple login page that I'm having some trouble with. When you type in incorrect info it just runs an alert, but I want it to add some CSS to the backgrounds of the fields that makes them red. How would I go about editing the following code to do this?
Here's the fiddle.
Thanks.
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
<title>Jeremy Blazé</title>
</head>
<body>
<div id="box">
<img src="logo.png" />
<form name="login">
<input type="text" name="userid" placeholder="Username" />
<input type="password" name="pswrd" placeholder="Password" />
<input type="submit" class="button" onclick="check(this.form)" placeholder="Password" value="Sign in" />
</form>
</div>
<script language="javascript">
function check(form) {
if(form.userid.value == "username" && form.pswrd.value == "password") {
window.open('dashboard/index.html')
}
else {
alert("Error Password or Username")
}
}
</script>
</body>
</html>
// js
else {
alert("Error Password or Username");
document.login.class = "error";
}
// css
form.error input[type="text"], form.error input[type="text"] {
background-color: red;
}
On error, you can do this:
form.userid.className = "invalid";
CSS
.invalid
{
border-style:solid;
border-width:2px;
border-color:red;
}
I would change your function slightly and run it on form onsubmit:
function check(form) {
var valid = true;
if (form.userid.value !== 'username') {
form.userid.className = 'error';
valid = false;
}
else {
form.userid.className = '';
}
if (form.pswrd.value !== 'password') {
form.pswrd.className = 'error';
valid = false;
}
else {
form.pswrd.className = '';
}
if (valid) {
window.open('dashboard/index.html');
}
return false; // return valid; if you want to submit the form once it's valid
}
HTML:
<form name="login" onsubmit="return check(this)">
CSS:
#box input.error {
border: 1px darksalmon solid;
background: #f0dddd;
}
Demo: http://jsfiddle.net/JLrQB/1/

focus textfield if javascript validation failed

I've this code:
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body>
<form name="frm" action="test.php">
Enter name:<input type="text" name="name" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit"/>
</form>
</body>
</html>
In above code, I'd tried to validate textfields when they lose focus. The script working fine if the name starts with A. But I want if the user enter different name which doesn't start with A it will return the focus to the textfield name. For that I'd written this script:
<script type="text/javascript">
var name = document.frm.name.value;
if(name.indexOf("A") == 0){
alert(name);
}else{
document.frm.name.focus();
}
</script>
then it doesn't works.
Anybody could help with that what should I do to request focus of textfield name?
I've only a little knowledge of javascript.
Just give an id for you form and refer it with document.getElementById('form_id'). Use of name attribute in this context has been deprecated over a decade ago. Also name for input should be something else than "name", rather use username or sth.
HTML:
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" id="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" id="email" onblur=""/>
</form>
JavaScript:
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
Instead of retrieving the id of the form, you can also pass the form to validate() as an argument: onblur="validate(this);". Then use that argument as a form in the eventhandler:
function validate(form){
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
form.username.focus();
}
}
EDIT
Focus doesn't seem to work without a delay, you can try this (the inputhas an id="username"):
function focusTo (elm) {
elm.focus();
return;
}
function validate(){
var form = document.getElementById('frm');
if (form.username.value.indexOf("A") === 0) {
alert(name);
} else {
alert('error');
setTimeout(function () {focusTo(form.username);}, 10);
}
}
modifiy your script like this
<html>
<head>
<script type="text/javascript">
function validate(){
var name=document.frm.name.value;
if(name.indexOf("A")==0){
alert(name);
}
}
</script>
</head>
<body >
<form id="frm" action="test.php">
Enter name:<input type="text" name="username" onblur="validate()"/>
Enter e-Mail:<input type="text" name="email" onblur=""/>
<input type="submit" onclick="check()"/>
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
alert(name);
document.getElementById('frm').email.focus();
}else{
document.getElementById('frm').username.focus();
}
}
function check()
{
var name = document.getElementById('frm').username.value;
if(name.indexOf("A") == 0){
}else{
alert("Please enter a name starting with 'A'");
document.getElementById('frm').username.focus();
}
}
//-->
</SCRIPT>
</body>
</html>
You want to execute function validate() on event onblur. in the script you have written the code for focusing, but not added it in a function.
try this document.frm.username.focus(); . i hope it will work.

Categories

Resources