off FUNCTION jquery - javascript

I am trying to make a validation form in a .php file , so it works in a way that once the field validation is done the form gets submitted . My form although is getting submitted but for that I need to press the submit button twice . Below is the code , the problem is mainly in the script section.
<!DOCTYPE html>
<html>
<head>
<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" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title></title>
<style type="text/css">
.container{
margin-top: 20px;
width: 500px;
}
#content{
resize: none;
}
#success{
display: none;
}
#failure{
display: none;
}
</style>
<body>
<div class="container">
<h1 class="display-3">Get in Touch</h1>
<div class="alert alert-danger" role="alert" id="failure">
</div>
<div class="alert alert-success" role="alert" id="success">
<strong>Well done!</strong> We will get back to you ASAP.
</div>
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" id="content" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>
<script type="text/javascript">
$( "form" ).submit(function( event ) {
event.preventDefault();
var missing="";
if($("#email").val()=="")
{
missing=missing+"<p>Email is Missing</p><br>"
}
if($("#content").val()=="")
{
missing=missing+"<p>Content is Missing</p><br>"
}
if($("#subject").val()=="")
{
missing=missing+"<p>Subject is Missing</p><br>"
}
if(missing!="")
{
$("#failure").html(" <strong>Oh snap!</strong><br>."+missing);
$("#failure").show();
}
else{
$("#failure").hide();
$("form").off("submit").submit(); <- Problematic line
}
});
</script>
</body>
</html>

The issue is here:
$("form").off("submit").submit()
Instead of this, use preventDefault to hold the form submit to check the validation, and when validation succeed submit the form using:
$("form").submit();

.off only removes events that were added using .on. It doesn't remove native events or anything like that.
You're already using event.preventDefault() to stop the native form submission, which is correct.
Therefore simply $("form").submit(); should be sufficient to submit the form programmatically, once your validation is complete.
P.S. I assume you are validating your form on the server (PHP) side as well? JavaScript validation is nice for enhanced user experience but you cannot rely on it, as a malicious user (or bot) can easily change by manipulating the page source, or just ignore it entirely and post to your URL. If you value the integrity of your server and your data you must always validate forms on the server side as well.

Instead of $("form").off("submit").submit(); you can use this.submit();

Try to switch the order of the 2 functions:
$("form").submit().off("submit");

Related

Javascript: Move JQuery etc. CDNs out of the HTML file?

(I'm new to HTML/JS). I'm trying to clean up my HTML file to bear-bone markup and put all logic in a .js file, including the CDN inclusions. I'm aware of How to include CDN in javascript file (*.js)?
In the HTML below, I tried to move the 2 'src' lines at the bottom, to form_validation.js, also shown below. But when I do that, the Semantic UI form validation stops working and I get error messages that .form is not a function etc. That addCDN() call in the JS file doesn't do it.
I imagine this has to do with me not understanding the order in which these things are processed by the browser... I would greatly appreciate some education.
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<style>.container {margin: 15em;}</style>
</head>
<body>
<div class="container">
<form class="ui form">
<p>Give this a try:</p>
<div class="field">
<label>Name</label>
<input placeholder="Your Name?" name="name" type="text">
</div>
<div class="ui submit button">Submit</div>
<div class="ui error message"></div>
</form>
</div>
<!-- get these guys out-a-here -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
<!-- ..... -->
<script src="form_validation.js"></script>
</body>
</html>
/*
* form_validation.js
* Uses Semantic UI validation JSON
*/
function addCDN(){
// Can be removed? Ideally not in the HTML file...
var jq = document.createElement('script');
jq.setAttribute('src',
'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'
);
document.head.appendChild(jq);
var sui = document.createElement('script');
sui.setAttribute('src',
'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js'
);
document.head.appendChild(sui);
}
$(document).ready(function(){
addCDN(); // this doesn't seem to happen :(
$('.ui.form').form({
fields: {name : ['minLength[6]', 'empty']}
});
});```

Hide an element and show another element on submit a form

In a web page, I would like to hide the form on submit (either by clicking or pressing enter) and shows the results. It does not work when the Go web server is run.
When I check the HTML file (without running the Go file), it works. But, when I run the Go code, it shows it quickly and goes to the initial state.
The HTML (Bootstrap) code is here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="" />
<meta name="google" value="notranslate">
<title>TEST</title>
<!-- favicon -->
<link rel="icon" type="image/png" href="../static/images/favicon.png">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="../static/css/style.css" />
<!-- scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.3/particles.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<style>
body {
background-color: #2f3b5a
}
.table thead th,
.table td,
.table th {
border: 0px;
text-align: center;
background-color: #c83660;
border-radius: 10px;
}
</style>
</head>
<body>
<!-- background particles -->
<canvas class="background" style="position: absolute; top: 0; bottom: 0; left: 0; right: 0; z-index: -1;"></canvas>
<div class="d-flex align-items-center flex-column justify-content-center text-white" style="width:100%;">
<h1 class="display-4">TOOL</h1>
<div class="container">
<div class="row">
<div class="col">
</div>
<div class="col-6">
<form class="forms">
<div class="input-group">
<div class="input-group-prepend">
<select class="selectpicker forms" name="query">
<option selected>Query Type</option>
<option value="any">Any</option>
<option value="aaaa">A Record</option>
</select>
</div>
<input type="text" class="form-control forms" name="host" placeholder="Type here...">
<div class="input-group-append">
<button type="button forms" class="btn"><i class="fas fa-search"
aria-hidden="true"></i></button>
</div>
</div>
</form>
<div id="result" style="display:none;">
<table class="table table-borderless">
<thead>
<tr>
<th scope="col">Record</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
{{range .Arecord}}
<td>{{.}}</td>
{{end}}
</tr>
</tbody>
</table>
</div>
</div>
<div class="col">
</div>
</div>
</div>
</div>
<!--scripts loaded here-->
<script src="https://kit.fontawesome.com/80c543b9b1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.13.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/bassjobsen/affix/master/assets/js/affix.js"></script>
<script>
window.onload = function () {
Particles.init({
selector: '.background',
// red, blue, yellow
color: ['#f76262', '#216583', '#f6d365'],
maxParticles: 130,
connectParticles: true,
responsive: [
{
breakpoint: 768,
options: {
maxParticles: 80
}
}, {
breakpoint: 375,
options: {
maxParticles: 50
}
}
]
});
};
$("form").on("submit", function (e) {
//e.preventDefault();
$("form").remove();
$("#result").show("slow");
});
</script>
</body>
</html>
I expect removing the form on submit and shows the results table but as long as I run the code in Go, it just restarts the page (quickly shows the results but) the form value is empty.
url := r.FormValue("host")
I may be totally off here, because I don't think I understand your problem completely, however it looks like you're trying to submit this form, and then display the results section without the form. I'm guessing your Go server is somehow preparing these results based on the form values.
If that is really the case, then what's happening is that you submit the form, your javascript hides the form and shows the empty results section, then your server prepares the results, and you display the form again. This time though, it is a completely new page and, it has no knowledge of the Javascript executed before form submission. It is a fresh new page, so it'll show the empty form, and not the results section.
If what I understand is correct, then what you should do is to change your template so that it knows it is displaying the results, so it builds the result section without display: none.
Sounds like you should use ajax call to send the request instead of form submit and based upon the response, display the result show/hide.

Bootstrap form: how to handle correctly "is-invalid" class assigned to an input validated on "change"? Outline color doesn't match "invalid-feedback"

I created a form using Bootstrap and I need that the outline of inputs of class "partIVAInput" becomes red and that red feedback message appears - not only when input are empty - but also when their value - checked by the "isValidPIVA(value)" function - is wrong.
The handler of "keyup blur change" for the input with class "partIVAInput" checks if the value and assign accordingly the classes "is-valid/invalid" to the input.
<!doctype html>
<html lang="it">
<head>
<!-- Required meta tags -->
<meta charset="ISO-8859-15">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script>
$(function () {
$(".numericInput, .partIVAInput, .capInput").bind("keyup blur change", function (event) {
var value = $(this).val();
if ($(this).hasClass("partIVAInput"))
if (!isValidPIVA(value)) {
$(this).removeClass("is-valid").addClass("is-invalid");
}
else {
$(this).removeClass("is-invalid").addClass("is-valid");
}
});
});
//------------------------------------------------------------------------
function isValidPIVA(value) {
return (value === "123" ? true : false);
}
//------------------------------------------------------------------------
</script>
<title>Test</title>
</head>
<body>
<div class="container">
<form id="frmIscrCant" class="needs-validation" novalidate="">
<div id="divDatiCommittente" class="card bg-light">
<h5 class="card-header">Dati</h5>
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-8">
<label for="tbEnte">Denominazione</label>
<input type="text" id="tbEnte" name="Ente" class="form-control" required="">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="tbPartIvaCommitt">Partita IVA</label>
<input type="text" id="tbPartIvaCommitt" name="PartIvaCommitt" class="form-control partIVAInput" required="">
<div class="invalid-feedback">Inserire una partita IVA valida (123)!</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Perhaps I'm not handling things well since I'm experiencing the following problem.
When I insert in the field a right value (OK)...
When I insert in the field a wrong value (OK)...
When I submit with a wrong value in the field (NO!!! The feedback message is correctly displayed but the outline of the input has become green while it must be red. Also if I write a new wrong value in the field the outline of the input continues to be green. Further, the form is submitted while with a field marked as "is-invalid" I guess it shouldn't)...
What's wrong?
PS
I created this new thread in replacement of this How can I validate a field using a JavaScript function? that can be closed/deleted.

The page will strangely refresh when I click the button

Here's my code:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>中国工程院无线投票系统</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="container" id="login">
<div class="col-md-6 col-md-offset-3">
<div class="page-header">
<h1>中国工程院无线投票系统</h1>
</div>
<form>
<div class="form-group">
<label>用户名</label>
<div class="input-group">
<div class="input-group-addon"><i class="glyphicon glyphicon-user"></i></div>
<input type="text" v-model="account.username" class="form-control" placeholder="Username" required
autofocus>
</div>
</div>
<div class="form-group">
<label>密码</label>
<div class="input-group">
<div class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></div>
<input type="password" v-model="account.password" class="form-control" placeholder="Password"
required>
</div>
</div>
<button v-on:click="validate" class="btn btn-lg btn-primary btn-block">登录</button>
</form>
</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios#0.12.0/dist/axios.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
In the login.js file:
var login = new Vue({
el:"#login",
data:{account:{}},
methods:{
validate:function () {
},
say: function (){
}
}
});
At the beginning, I thought it had something to do with the code within method "validate". However, after I deleted all the code inside, the page still get refreshed when I click the button which is not supposed to happen.
You should add type="button" to your <button>.
If you don't specify a type of a <button> in a <form>, it will behave like a submit button by default, which refreshes the page.
Docs:
<type="submit"> The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
Or you can do it the vuejs way using Event modifiers like this:
<button v-on:click.prevent="validate" class="btn btn-lg btn-primary btn-block">登录</button>
The prevent event modifier prevents the default behaviour.
Its just like using event.preventDefault() inside your event handler
Add #submit.prevent to your form.
<form #submit.prevent>
....
</form>
When using a form element, the submit action refreshes the page unless you specify return false; at the end of the onsubmit attribute. I believe you are having the same issue here.
Try putting a semicolon at the end of your onclick attribute (before the quote), then type return false; and it should solve your problem.

How to show angular input error state outside of form

I have the requirement, that all error messages have to be shown in the header of the application. How can I do that with angular?
If I have this application (see on plunker):
<body>
<div id="header">
<!-- I want error messages to show up here -->
</div>
<form name="myForm">
<label>Email</label>
<input name="myEmail" type="email" ng-model="user.email" required="" />
<div ng-messages="myForm.myEmail.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
<p>Your email address is: {{user.email}}</p>
</body>
What I need is to have the error messages in the header div. How can I do that?
Fixed demo here.
Just access the error the way same as in form, as when you set <form name="myForm" >, then you will get $scope.myForm = [yourFormObject], then access free anywhere in same controller.
Angular Form Document
Under the title Binding to form and control state
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
And, even access the $error in controller by $scope.$watch('formName.fieldName.$error',function(nv,ov){});
// Code goes here
var app = angular.module('plunker', ['ngMessages']);
app.controller('appCtrl', function($scope) {
$scope.$watch('myForm.myEmail.$error', function(nv, ov) {
console.info(nv);
}, true);
});
/* Styles go here */
hr {
margin: 20px 0;
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
</script>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular-messages.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="appCtrl">
<div id="header">
<div ng-show="myForm.myEmail.$error.required">required</div>
<div ng-show="myForm.myEmail.$error.email">invalid email</div>
</div>
<hr />
<form name="myForm">
<label>Email</label>
<input name="myEmail" type="email" ng-model="user.email" required="" />
<div ng-messages="myForm.myEmail.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
<p>Your email address is: {{user.email}}</p>
</body>
</html>
You'll have two distinct controller.In header controller, you'll be displaying your error messages.
Then your controller will be communicating over either $rootScope or service

Categories