jQuery preventDefault() not working and syntax error - javascript

Basically I'm trying to make a form validation using jQuery etc..
I'm trying to use the event.preventDefault(); function to prevent the form from submitting the default way.
It doesn't seem to be working.
I am also trying to make an if statement that checks if its a valid email adress but it's giving be syntax error for some reason.
Hoow do I fix these issues?
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<style>
#wrapper {
margin: 0 auto;
width: 600px;
font-family: helvetica;
font-size: 1.2em;
}
input {
width: 300px;
height: 30px;
padding: 7px;
border-radius: 5px;
font-size: 1.2em;
border: 1px solid grey;
margin-bottom: 10px;
}
label {
width: 200px;
float: left;
padding-top: 10px;
}
#submitButton {
height: 50px;
margin-left: 200px;
width: 100px;
}
</style>
<body>
<div id="wrapper">
<form id="validationForm">
<label for="email">Email</label>
<input name="email" id="email" />
<label for="phone">Telephone</label>
<input name="phone" />
<label for="pass">Password</label>
<input name="pass" type="password" />
<label for="pass">Confirm Password</label>
<input name="pass" type="password" />
<input id="submitButton" type="submit" value="Submit" />
</form>
</div>
<script type="text/javascript">
$("#validationForm").submit(function(event) {
// this is the preventdefault that isn't working.
event.preventDefault();
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
}
// It's giving me syntax error for the '{' in the beginning of this if //statement.
if (!isValidEmailAddress($("#email").val()) {
alert("hello");
}
});
</script>
</body>
</html>

You're missing a closing ) in this line:
if (!isValidEmailAddress($("#email").val()) {
Should be:
if (!isValidEmailAddress($("#email").val())) {
Notice you have 4 ( and only 3 )? That's the issue. Look into using an IDE when editing code, it would have picked up this issue instantly.
Edit
Also, the syntax error was causing the event.preventDefault() to not fire, so this fix will solve that as well.

It looks like your code syntax needs some correction:
<script type="text/javascript">
$("#validationForm").on('submit', function(event) {
event.preventDefault();
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
}
if (!isValidEmailAddress($("#email").val())) {
alert("hello");
}
});
</script>
Here is DEMO

Related

Why is my Button Not Working in Electron JS?

So I'm working on a small desktop app for myself, and for some reason I can't get the buttons to do anything. I am using skeleton CSS. I was able to get buttons working using this method previously, but for some reason it's no longer working.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="skeleton.css" type="text/css">
<head>
<h3>Which Term is Correct?</h3>
</head>
<body>
<div class="form">
<label>First Search Term</label>
<input type="text" name="name">
<label>Second Search Term</label>
<input type="text" name="email">
<input id="subButton" type=submit value="Submit">
<input id="histButton" type=submit value="History">
<input id="exitButton" type=submit value="Terminate">
</div>
<script>
const remote = require('electron').remote;
document.querySelector('#exitButton').addEventListener('click', () => {
let w = remote.getCurrentWindow()
w.close();
})
</script>
</body>
<style type="text/css">
.form {
margin: 0 auto;
width: 210px;
text-align:center
}
.form label{
display: inline-block;
text-align: right;
margin-left: auto;
margin-right: auto
}
.form input{
display: inline-block;
text-align: left;
margin-left: auto;
margin-right: auto
}
</style>
</html>
You typed
<input id="subButton" type=submit value="Submit">
You should be typing
<input id="subButton" type="submit" value="Submit">
Notice the quotation marks around submit. See if this solves it.

How to store the results of this function in an individual array for every input entered in the form?

function post(event) {
event.preventDefault();
const data = document.getElementById("data");
var nameValue = document.getElementById("name").value;
const pname = document.getElementById("pname").value;
const ptype = document.getElementById("ptype").value;
const name = document.createElement("p");
name.appendChild(document.createTextNode(nameValue));
name.setAttribute("class", "perName");
data.appendChild(name);
const product_type = document.createElement("p");
product_type.appendChild(document.createTextNode(ptype));
product_type.setAttribute("class", "prodType");
data.appendChild(product_type);
const product_name = document.createElement("p");
product_name.appendChild(document.createTextNode(pname));
product_name.setAttribute("class", "prodName");
data.appendChild(product_name);
document.getElementById("myForm").reset();
}
*,
body {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#myForm {
display: flex;
flex-direction: column;
padding: 30px;
margin: 10%;
border: 1px solid;
}
label {
padding-top: 7px;
}
input[type="text"] {
padding: 10px;
margin-top: 10px;
}
button[type="submit"] {
background-color: black;
color: white;
padding: 10px;
margin-top: 10px;
}
#data {
display: flex;
flex-direction: column;
align-items: center;
background-color: yellow;
width: 80%;
margin: auto;
}
.datas {
background-color: teal;
padding: 5px;
}
footer {
margin-top: 2%;
padding: 10%;
background-color: tomato;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Share and care</title>
</head>
<body>
<!-- body -->
<form id="myForm" onsubmit="return post(event);">
<label for="">Name</label>
<input type="text" name="personName" id="name" />
<label for="">Your product</label>
<input type="text" name="" id="ptype" />
<label for="">Product Name</label>
<input type="text" name="" id="pname" />
<button type="submit">Post</button>
</form>
<!-- inputdisplay -->
<div class="datas">
<div id="data"></div>
</div>
<div id="result"></div>
<footer></footer>
<script src="script.js"></script>
</body>
</html>
Hello devs! I am a newbie webdev. Pls help me solve this basic problem.
Here I have three text fields. So every time the submit button is clicked the input values are stored and a new <p> is created for every input and there are displayed below. Now i need to get the values from that function and store in array. So everytime a submit is clicked the new object is to be pushed inside the array for individual persons
Start by creating an empty array (outside of the submit handler function)
const arr = [];
To push the data to the array, on every submit, do:
arr.push({ name: nameValue, productType: ptype, productName: pname });

Hey, how can I validate the user name and password? It's seems that the javascript don't get the values

I want to validate the user name and password, if the name and password are correct so by clicking "Enter" the user will move to another browser page But I can't take the values the user wrote to the JS (I put a link to YouTube because I don't know how to link to another HTML page)
I would be very happy for some help..
Thanks!
let form = document.getElementById('login').innerHTML;
let password = document.getElementById('passwordbox').innerHTML.value;
let Enter = document.getElementById('Enter').innerHTML.value;
let user = document.getElementById('userlogbox').innerHTML.value;
function check(form)
{
if (form.userid.value == 'abcd') {
window.open('https://www.youtube.com');
} else {
alert("the username you enterd not match");
}
}
function check(form) {
if (form.password.value == '1234') {
window.open('https://www.youtube.com');
} else {
alert("the password you enterd not match");
}
}
body {
margin: 0;
padding: 0;
font-family: sans-serif;
background: url(bg.jpg) no-repeat;
background-size: cover;
}
.login-box {
width: 280px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
}
.login-box h1 {
float: left;
font-size: 40px;
border-bottom: 6px solid #4caf50;
margin-bottom: 50px;
padding: 13px 0;
}
.textbox {
width: 100%;
overflow: hidden;
font-size: 20px;
padding: 8px 0;
margin: 8px 0;
border-bottom: 1px solid #4caf50;
}
.textbox i {
width: 26px;
float: left;
text-align: center;
}
.textbox input {
border: none;
outline: none;
background: none;
color: white;
font-size: 18px;
width: 80%;
float: left;
margin: 0 10px;
}
.btn {
width: 100%;
background: none;
border: 2px solid #4caf50;
color: white;
padding: 5px;
font-size: 18px;
cursor: pointer;
margin: 12px 0;
}
<form id='login' class='login'>
<div id='userlogbox' class="login-box">
<h1>Sudoku</h1>
<div class="textbox">
<i class="fas fa-user"></i>
<input type="text" placeholder="Username" name="userid">
</div>
<div id='passwordbox' class="textbox">
<i class="fas fa-lock"></i>
<input type="password" placeholder="Password" name="password">
</div>
<button><input id='Enter' type="button" class="btn" value="Enter" onclick="check(this.form)" value="Enter"/>
</button>
</div>
</form>
I’m still learning, so it seems like a disaster, but thanks
the thing is that I can't use something we haven't learned yet - addEventListener
So I tried to write like that, you helped me a lot, I'd love to hear why you think it doesn't work
JS
const form = document.getElementById('login');
const userName = document.getElementById('userId');
const password = document.getElementById('userPassword');
const enterBtn = document.getElementById('enter');
const allowedUser = 'abcd';
const allowedPwd = '1234';
enterBtn.onclick() = function(){
if (!userName.value || !password.value) {
prompt('Please enter user & password');
return;
}
else if (password.value != '1234') {
prompt('Please enter password');
return;
}
else if (userName.value != 'abcd') {
prompt('Please enter user');
return;
}
else if (userName.value === allowedUser && password.value === allowedPwd) {
window.location.href = "/Users/ormor/Desktop/Sudoku%20Project%204/Sudoku%20Project/main/";
}
else {
prompt('the username you entered does not match');
return;
}
}
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='ws.css'>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class='rows'>
<form id='login' class='login'>
<div id='userlogbox' class="login-box">
<h1>Sudoku</h1>
<div class="textbox">
<i class="fas fa-user"></i>
<input id="userId" type="text" placeholder="username" name="userid">
</div>
<div id='passwordbox' class="textbox">
<i class="fas fa-lock"></i>
<input id="userPassword" type="password" placeholder="password" name="password">
</div>
<button id='enter' type="button" class="btn btn-danger" onclick="validCheck()">Enter</button>
</div>
</div>
</div>
</div>
</form>
</body>
<script src='ws.js' defer></script>
</html>
CSS
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding-top: 120px;
background: url(33v2wnher48y.jpg) no-repeat;
background-size: 30%;
background-position: 35px, 35px, 35px, 35px;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
flex-direction: column;
}
Please remove parentesis in your btnEnter.onclick
The code is a disaster (many typo error) and i do not understand very well because you do not check also password...however im try to help you because im studing javascript in this moment.
const form = document.getElementById('login');
const userName = document.getElementById('userId');
const password = document.getElementById('userPassword');
const enterBtn = document.getElementById('enter');
const allowedUser = 'abcd';
const allowedPwd = 'something';
enterBtn.addEventListener('click', (event) => {
event.preventDefault();
if (!userName.value || !password.value) {
alert('Please enter user & passowrd');
return;
}
if (userName.value === allowedUser && password.value === allowedPwd) {
window.open('https://www.youtube.com');
} else {
alert('the username you enterd not match');
}
});
I delete the css file (your html and js are fill of typo error and other bad practice)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='script.js' defer></script>
</head>
<body>
<form id='login' class='login'>
<div id='userlogbox' class="login-box">
<h1>Sudoku</h1>
<div class="textbox">
<i class="fas fa-user"></i>
<input id="userId" type="text" placeholder="username" name="userid">
</div>
<div id='passwordbox' class="textbox">
<i class="fas fa-lock"></i>
<input id="userPassword" type="password" placeholder="password" name="password">
</div>
<button id='enter' type="button" class="btn">
Enter
</button>
</div>
</form>
</body>
</html>

bootstrap-validate: How can i enable validation in bootstrap4?

I have a validation form in bootstrap4 when I enter less than 5 characters it shows me an error.
When I enter 5 or more than 5 characters I want to put a green check-mark and border on that particular input field.
<div class="container">
<form action="" class="needs-validation" novalidate>
<div class="form-group">
<label for="username">username:</label>
<input type="text" class="form-control" id="name" placeholder="username" required>
</div>
<input type="submit" class="btn btn-primary" value="submit" >
</form>
</div>
<script src="./dist/bootstrap-validate.js"></script>
<script>
bootstrapValidate('#name', 'min:5:Enter at least 5 charecters');
</script>
</body>
</html>
https://github.com/NinoosMoshi/form-validation.git
You need a few things in your code...
you got the condition correct, need to add/remove classes as a result of bootstrapValidate
import the icon library (i used font awesome v5)
in the classes you add/remove, you gotta place the icon for the check mark
UPDATE:
in light of questioner's comment of multiple fields in the form
Following code should help:
$(document).ready(function() {
bootstrapValidate('#usr', 'min:5:Enter at least 5 characters!', function(isValid) {
if (isValid) {
$("#formHolder").addClass('validClass');
$("#formHolder").removeClass('invalidClass');
} else {
$("#formHolder").addClass('invalidClass');
$("#formHolder").removeClass('validClass');
}
});
bootstrapValidate('#lastName', 'min:7:Enter at least 7 characters!', function(isValid) {
if (isValid) {
$("#formHolder2").addClass('validClass');
$("#formHolder2").removeClass('invalidClass');
} else {
$("#formHolder2").addClass('invalidClass');
$("#formHolder2").removeClass('validClass');
}
});
});
.validClass>input {
border: 2px solid green;
}
.validClass .form-control:focus {
border-color: green;
box-shadow: 0 0 0 0.2rem rgba(33, 93, 30, 0.56)
}
.invalidClass>input,
.invalidClass .form-control:focus {
border: 2px solid red;
}
.inputWrapper {
display: inline-block;
position: relative
}
.validClass:after {
font-family: "Font Awesome 5 Free";
content: "\f00c";
visibility: visible;
font-weight: 900;
color: green;
position: absolute;
right: 6px;
top: 55%;
}
.invalid-feedback {
position: absolute;
display: inline-block;
bottom: -100px;
left: 0px;
}
.submitBtn {
margin-top: 20px;
}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.rawgit.com/PascaleBeier/bootstrap-validate/v2.2.0/dist/bootstrap-validate.js"></script>
<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
<div class="container mt-3">
<form>
<div class="form-group">
<div class='inputWrapper invalidClass' id='formHolder'>
<label for="usr">Name:</label>
<input type="text" class="form-control " id="usr">
</div>
<br/>
<div class='inputWrapper invalidClass' id='formHolder2'>
<label for="lastName">last Name:</label>
<input type="text" class="form-control " id="lastName">
</div>
</div>
<button type="submit" class="btn btn-primary submitBtn">Submit</button>
</form>
</div>

Disabling error messages when using the JQuery validator extension

I've searched around for a way to disable the error messages that are displayed next to invalid form elements and I have only found ways to customize the messages, not prevent them altogether.
I tried:
jQuery.extend(jQuery.validator.messages, {
required: ""
}
But that still places a blank space next to my text boxes and throws off the positioning. Anyone know a way that I can do this?
$('#submit').click(function(){
$("#contactform").validate({
errorPlacement: function(error, element) { },
debug:true
})
});
leaving the errorPlacement line blank did the trick.
You could use CSS to hide them
label.error { display:none; }
It's not a perfect solution, but it'll work
I created an over-ride of the existing "required" validator to return no error messages.
Over-Ride Required Method:
// Creates the NEW validator method
jQuery.validator.addMethod('requiredNoMsg', jQuery.validator.methods.required, '');
// Creates a new CSS Rule for the validator method
// so we can add it like "class='requriedNoMsg'".
jQuery.validator.addClassRules('requiredNoMsg', { requiredNoMsg: true });
Full Example:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Demo</title>
<!-- jQuery 1.6.1 -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" charset="utf-8"></script>
<!-- jQuery Validate 1.8.1 -->
<script type="text/javascript" src="https://github.com/jzaefferer/jquery-validation/raw/master/jquery.validate.js" charset="utf-8"></script>
<script type="text/javascript" src="https://github.com/jzaefferer/jquery-validation/raw/master/additional-methods.min.js" charset="utf-8"></script>
<style type="text/css">
body { margin: 0; padding: 0; font-family: Verdana, Tahoma, Arial, sans-serif; }
fieldset.main { margin: 1em; padding: 1em; width: 400px; font-size: .9em; }
fieldset.main ol { padding: 1em 1em 0 1em; list-style: none; }
fieldset.main li { padding-bottom: .5em; }
fieldset.main ol li label { display: block; width: 12em; margin-right: 1em; }
input[type=button] { width: 6em; height: 2.5em; }
input[type=checkbox] { }
input[type=text].error { border: 1px dotted red; background-color: yellow;}
</style>
<script type="text/javascript">
jQuery.validator.addMethod('requiredNoMsg', jQuery.validator.methods.required, '');
jQuery.validator.addClassRules('requiredNoMsg', { requiredNoMsg: true });
$(document).ready(function () {
$('#myform').validate(
{submitHandler: function () { alert('Validation Passed!'); }}
);
});
</script>
</head>
<body>
<form id="myform" method="get" action="">
<fieldset class="main">
<ol>
<li>
<label for="CustomerCode" class="left">
Customer Code</label>
<input type="text" id="CustomerCode" name="CustomerCode" class="requiredNoMsg" />
</li>
<li>
<label for="DeliveryCode" class="left">
Delivery Code</label>
<input type="text" id="DeliveryCode" name="DeliveryCode" class="requiredNoMsg" />
</li>
<li>
<input type="submit" id="Add" value="Add" />
</li>
</ol>
</fieldset>
</form>
</body>
</html>

Categories

Resources