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

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>

Related

Multi-Part HTML Form Validating Only Some Inputs

I have this multi-part HTML form... I know it is a bit messy! I am working on it!
I want the validation to work but only work on the inputs that are not disabled. I want to make it so on the dropdowns when the text inputs are not disabled, it checks them but when they are disabled, they don't be checked!
How?
<?php
$conn = mysqli_connect("localhost", 'admin', 'myphpadmin', 'tests');
$qm = "Select Name From options Where `Type` = 'Merchant'";
$merchant = mysqli_query($conn, $qm);
$qt = "Select Name From options Where `Type` = 'Type'";
$type = mysqli_query($conn, $qt);
$qs = "Select Name From options Where `Type` = 'Source'";
$source = mysqli_query($conn, $qs);
$qsub = "Select Name From options Where `Type` = 'Sub'";
$sub = mysqli_query($conn, $qsub);
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='stylesheet' href='../Bootstrap/css/bootstrap.css'
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
</style>
<body>
<form id="regForm" action="multi.php">
<h1>Add Transaction</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Details
<p><input placeholder="Description" oninput="this.classList.remove('invalid')" class='form-control' name="description"></p>
<p><input oninput="this.classList.remove('invalid')" name="date" type='date' class='form-control'></p>
<p><input placeholder='Amount' oninput="this.classList.remove('invalid')" name="amount" type='number' step='0.01' class='form-control'></p>
</div>
<div class="tab">Merchant
<p>
<select oninput="this.classList.remove('invalid')" onchange='merch(this.value)' name="merchant" class='form-control'>
<option value='' disable selected hidden>Select Merchant</option>
<?php
while($row = mysqli_fetch_assoc($merchant)){
foreach($row as $val){
echo "\t\t\t\t\t\t<option value='$val'>$val</option>\n";
}
}
?>
<option value='other'>Other</option>
</select>
</p>
<p><input type='text' name='om' class='form-control omerch' placeholder='Other Merchant' disabled></p>
<p><input type='checkbox' name='am' class='form-check-input omerch' id='om' disabled><label for='om' >&nbspAdd To Merchants List?</label></p>
</div>
<div class="tab">Type
<p>
<select oninput="this.classList.remove('invalid')" onchange='checktype(this.value)' name="type" class='form-control'>
<option value='' disable selected hidden>Select Type</option>
<?php
while($row = mysqli_fetch_assoc($type)){
foreach($row as $val){
echo "\t\t\t\t\t\t<option value='$val'>$val</option>\n";
}
}
?>
<option value='other'>Other</option>
</select>
</p>
<p><input type='text' name='ot' class='form-control otype' placeholder='Other Type' disabled></p>
<p><input type='checkbox' name='at' class='form-check-input otype' id='ot' disabled><label for='ot' >&nbspAdd To Types List?</label></p>
</div>
<div class="tab">Sub:
<p>
<select oninput="this.classList.remove('invalid')" onchange='checksub(this.value)' name="sub" class='form-control'>
<option value='' disable selected hidden>Select Sub-Type</option>
<?php
while($row = mysqli_fetch_assoc($sub)){
foreach($row as $val){
echo "\t\t\t\t\t\t<option value='$val'>$val</option>\n";
}
}
?>
<option value='other'>Other</option>
</select>
</p>
<p><input type='text' name='os' disabled class='form-control otype' placeholder='Other Sob' ></p>
<p><input type='checkbox' name='as' class='form-check-input osub' id='ot' disabled><label for='ot' >&nbspAdd To Subs List?</label></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
<script>
function merch(value){
console.log(value);
if(value == 'other'){
$('.omerch').removeAttr('disabled');
console.log('enabled')
}
else{
$('.omerch').attr('disabled','disabled');
console.log('disabled')
$('input[type="checkbox"].omerch').attr('checked', false);
$('input[type="text"].omerch').val('');
}
}
</script>
</body>
</html>
Does anyone know how to do this? I used input:enabled, input:not(:disabled)... Nothing worked!
Thanks!
You need to just change one line and you can do this with JS itself rather than with your selector:
if (y[i].value == "")
to
if (y[i].value == "" && !y[i].disabled) {
Basically we say, is it blank and not (!) disabled.
Or if you do want to do it with CSS selectors it is
input:not([disabled]) as disabled is an attribute and you need to use the attribute selector ([]).
Also you are using getElementByTagName - use querySelectorAll instead as otherwise you are limited in the CSS you can use (Tag Name is for the element type such as input, button etc. so you can't use CSS selectors there).
Full Validator Code JS way
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
///////////////////////////////////CHANGED HERE////////////////////////////
// If a field is empty and NOT disabled...
if (y[i].value == "" && !y[i].disabled) {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Full Validator code CSS way
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
///////////////////////////////////CHANGED HERE////////////////////////////
y = x[currentTab].querySelectorAll("input:not([disabled])");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
A quick note
You may want to look into the :valid psuedo selector. It has the added benefit that you get some native checks for validation if you give the input a type attribute. It will also be invalid if you have an empty field provided you use the required attribute.
I have stolen the example from the MSDN page and added it below to show you how easy it can make life, not a single line of JS there.
You could then query your inputs with input:valid and input:invalid within your JavaScript so it makes life easier there too.
That gives you a good grounding and a nice fallback incase your JS fails for any reason, but JavaScript is still useful to improve the accessibility.
Finally if you do decide to use the :valid and :invalid pseudo selectors and still want to perform some custom validation on top you can use the setCustomValidity function so you can rely on them solely (not a lot of people seem to know about this!)
input + span {
position: relative;
}
input + span::before {
position: absolute;
right: -20px;
top: 5px;
}
input:invalid {
border: 2px solid red;
}
input:invalid + span::before {
content: '✖';
color: red;
}
input:valid + span::before {
content: '✓';
color: green;
}
<form>
<fieldset>
<legend>Feedback form</legend>
<p>Required fields are labelled with "required".</p>
<div>
<label for="fname">First name: </label>
<input id="fname" name="fname" type="text" required>
<span></span>
</div>
<div>
<label for="lname">Last name: </label>
<input id="lname" name="lname" type="text" required disabled>
<span></span>
</div>
<div>
<label for="email">Email address (): </label>
<input id="email" name="email" type="email" required>
<span></span>
</div>
<div><button>Submit</button></div>
</fieldset>
</form>

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>

Detect the error message in the input field

How can I show the message if the user types a restricted symbol?
For example, if the user types * in the input field, the error message can show A filename cannot contain any of the following characters: \/:*?"<>|. I hope someone can guide me how to do it. Thanks.
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
</body>
</html>
<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
return false;
};
</script>
My expected result is like below the picture if the user types the restrict symbol in the input field:
Use the input event along with a regular expression, like so:
const input = document.getElementById("function_code");
const error = document.getElementById('error');
const regex = /[\\\/:*?"<>|]+/;
input.addEventListener('input', (e) => {
const value = e.target.value;
if (regex.test(value)) {
input.value = value.slice(0, value.length - 1);
error.textContent = 'A filename cannot contain any of the following characters: \/:*?"<>|';
} else {
error.textContent = '';
}
});
input {
padding: 8px 10px;
border-radius: 5px;
font-size: 1.2rem;
}
#error {
display: block;
color: red;
margin: 5px 0 0 0;
}
<input type="text" id="function_code" name="function_code">
<span id="error"></span>
Firstly I would wrap the input in a form.
After that you can use the setCustomValidity function for the input field to set a custom message if the condition is true. When you hit enter, or submit the form, you will see the error message.
This way you can give any custom message for your input.
Pay attention to the else block for handling no error cases.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<form>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0) {
this.setCustomValidity('A filename cannot contain any of the following characters: \/:*?"<>|');
} else {
this.setCustomValidity('');
}
};
</script>
</body>
</html>
Use HTML5 Pattern Match, below I have used the pattern ([a-zA-Z0-9]+) which simply means characters only latin alphabet and numbers 0-9. You can include the space character with
([a-zA-Z0-9]+\s{1}[a-zA-Z0-9]+)
You can learn more about regex here
This will not prevent author from entering wrong keypresses, it will only validate input. I will Include another approach to show custom error.
<form >
<input type="text" class="form-control blank" id="function_code" name="Option an" title="A name cannot contain irregular characters" pattern='([a-zA-Z0-9]+)' onpaste="return false">
<button >Submit</button>
</form>
Second approach. Use Javascript and write error to a div tag.
<!DOCTYPE html>
<html>
<body>
<h1>How to show error message</h1>
<input type="text" class="form-control blank" id="function_code" name="function_code" title="function_code" onpaste="return false">
<div id="error-box"></div>
</body>
</html>
<script>
function showError (key) {
var errBox = document.querySelector("#error-box");
errBox.textContent = "The character " + key.toString() + " is not allowed!";
//Dismiss the error
window.setTimeout(function () {
errBox.textContent = "";
}, 10000)
}
document.getElementById("function_code").onkeypress = function(e) {
var chr = String.fromCharCode(e.which);
if ("></\":*?|".indexOf(chr) >= 0)
showError(chr)
return false;
};
</script>

Change the colour of this input text depending on the value being entered

I have this input text:
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I would like to change the border of the input dynamically as the user is typing depending what the value is.
This value will be a percent based on an earlier defined amount that will change depending on the value the user is adding.
So if the value is under 5% it's red between 5-10% it's amber and over 10% is green etc.
Any JavaScript whizzes out there know the best way to do this?
I'll go with 2 events. The first is input, but contenteditable elements won't fire an input event on IE11, so I'll go for keypress with a timeout too.
input will be fired right after a user inputs something and the value is changed. keypress will fire after a user inputs something but right before the value is changed, in between.
This way you will keep all modern and older browsers covered (to a limit, because of addEventListener):
var tim = null;
var el = document.getElementById("newPrice");
el.addEventListener("keypress", function() {
tim = setTimeout(input, 0);
});
el.addEventListener("input", function input() {
clearTimeout(tim);
// do whatever you want with el.value
if (el.value == "BLAH") {
el.style.backgroundColor = "red";
} else if (parseInt(el.value) > 10) {
el.style.backgroundColor = "green";
} else if (parseInt(el.value) < -12) {
el.style.backgroundColor = "whizzeblue";
}
});
<input id="txt" type="number" onkeyup="changeborder(this.id, this.value)" />
<script type="text/javascript">
function changeborder(id, value){
if(value < 5){
document.getElementById(id).style.border = "2px solid red";
}
else if(value > 5 && value < 10 ){
document.getElementById(id).style.border = "2px solid yellow";
}
}
</script>
Use focusout . In snippet validation is not applied.
$("#newPrice")
.focusout(function() {
var price = $(this).val();
if (parseInt(price) <= 5) {
$(this).removeClass('green');
$(this).removeClass('blue');
$(this).addClass('red');
}
if (parseInt(price) > 5 && parseInt(price) <= 10) {
$(this).removeClass('red');
$(this).removeClass('blue');
$(this).addClass('green');
}
if (parseInt(price) > 10) {
$(this).removeClass('green');
$(this).removeClass('red');
$(this).addClass('blue');
}
});
.red {
border: solid 2px red;
}
.green {
border: solid 2px green;
}
.blue {
border: solid 2px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>

Using the Enter key to Access Submit Button in HTML

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.

Categories

Resources