AngularJS: Reset form on submit - javascript

I'm using an AngularJS form for a contact form and would like to reset the form on successful submission. I've found plenty of examples of how to reset an AngularJS Form and have that working, however, I've been unable to figure out a way to successfully reset the form on submission. My reset() function clears the form fields and appears to set the state of the form back to pristine when called on submit, however, the messages that should only be shown when a field is invalid are still displayed.
Here's my controller code with the function...
function ContactCtrl() {
var vm = this;
vm.reset = reset;
vm.submit = submit;
function reset(form) {
if (form) {
vm.name = undefined;
vm.email = undefined;
form.$setValidity();
form.$setPristine();
form.$setUntouched();
}
}
function submit(form) {
if (form) {
vm.reset(form);
}
}
}
The full code can be found below or on Plunker
angular
.module('plunker', [])
.controller('ContactCtrl', ContactCtrl);
function ContactCtrl() {
var vm = this;
vm.reset = reset;
vm.submit = submit;
function reset(form) {
if (form) {
vm.name = undefined;
vm.email = undefined;
form.$setValidity();
form.$setPristine();
form.$setUntouched();
}
}
function submit(form) {
if (form) {
vm.reset(form);
}
}
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ContactCtrl as contact">
<form name="form" novalidate>
Name:
<input type="text" ng-model="contact.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="contact.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
<input type="button" ng-click="contact.reset(form)" value="Reset" />
<input type="submit" ng-click="contact.submit(form)" value="Submit" />
</form>
<pre>
FORM:
form.$pristine = {{form.$pristine}}
form.$dirty = {{form.$dirty}}
form.$submitted = {{form.$submitted}}
NAME:
form.uName.$pristine = {{form.uName.$pristine}}
form.uName.$dirty = {{form.uName.$dirty}}
form.uName.$valid = {{form.uName.$valid}}
form.uName.$invalid = {{form.uName.$invalid}}
EMAIL:
form.uEmail.$pristine = {{form.uEmail.$pristine}}
form.uEmail.$dirty = {{form.uEmail.$dirty}}
form.uEmail.$valid = {{form.uEmail.$valid}}
form.uEmail.$invalid = {{form.uEmail.$invalid}}
</pre>
</body>
</html>

you could put the function you want to run on-submit inside of an ng-submit directive, this appears to get executed the same as the reset button:
<form name="form" ng-submit="contact.submit(form)">

Try the following, adding ng-submit
<form name="form" novalidate ng-submit="contact.submit(form)">
It worked for me.
Your button should look like this now
<input type="submit" value="Submit" />
hope this helps.

I also found that if you want to still use the form submit instead of ng-submit event, you need to wrap your form clearing code in a $timeout function. This forces the code you stick inside the $timeout to execute 'synchronously' to any other event actions (in this case the form submit).
Modified Plunkr seen here
angular
.module('plunker', [])
.controller('ContactCtrl', ['$scope','$timeout', ContactCtrl]);
function ContactCtrl($scope, $timeout) {
var vm = this;
vm.reset = reset;
vm.submit = submit;
vm.resetMe = resetMe;
function reset($event, form) {
if ($scope.form) {
$timeout(function(){
vm.name = undefined;
vm.email = undefined;
$scope.form.$setValidity();
$scope.form.$setPristine();
$scope.form.$setUntouched();
});
}
}
function submit(form) {
if (form) {
vm.reset(form);
}
}
function resetMe(){
console.log($scope);
debugger;
$scope.form.$setPristine();
}
}

Related

Accessing HTML service form object

I'm working through https://developers.google.com/apps-script/guides/html/communication trying to submit a form with info loaded from a google sheet. On the client side I have (Based heavily on the form example in the article) :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
// window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
// function updateUrl(url) {
// var div = document.getElementById('output');
// div.innerHTML = 'Got it!';
// }
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<div>
<select id="optionList" name="email">
<option>Loading...</option>
</select>
</div>
<br>
<div>
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
</div>
<input type="submit" value="Submit" />
</form>
On the server side (code.gs) I have:
function processForm(formObject) {
Logger.log('in here');
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
return driveFile.getUrl();
}
I can see that the submit is working because I see 'in here' in the logs. How can I access the form fields from within the processForm function?
This chunk doesn't make sense to me
var formBlob = formObject.myFile;
Your form doesn't contain the input whose 'name' attribute is set to 'myFile'. Once you click 'submit', the 'formObject' variable will be:
{
email: "Loading...", //from <select id="optionList" name="email">
message: "The cat was playing in the garden." //from <textarea name="message">
}

HTML onsubmit event is not calling the JavaScript function

I have two buttons in my form for calling two JavaScript functions. The first button works good in its onclick event calling the payroll() function successfully but the second button is of type submit and it never calls the send() function on form submission. I don't know why this issue occurs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html >
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{{ g.sijax.get_js()|safe }}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript" >
function payroll() {
var basic=document.forms["salary"]["bsalary"].value;
var empid=document.forms["salary"]["empid"].value;
var ta,hra,da,pf,netsalary,grosssalary;
if (empid == ""||basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if(isNaN(basic))
{alert("Salary must be in Numbers");
return false;
}
hra=basic*40/100;
da=basic*15/100;
pf=basic*12/100;
basic=parseInt(basic);
hra=parseInt(hra);
da=parseInt(da);
grosssalary=basic + hra + da;
ta=basic*6.2/100;
netsalary=grosssalary-ta;
document.getElementById("hra").innerHTML=hra;
document.getElementById("ta").innerHTML=ta;
document.getElementById("da").innerHTML=da;
document.getElementById("netsalary").innerHTML=netsalary;
document.getElementById("pf").innerHTML=pf;
document.getElementById("grosssalary").innerHTML=grosssalary;
window.alert("HI"+grosssalary);
return true;
}
function send()
{
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.forms['salary']['hra'].value;
var da = document.forms['salary']['da'].value;
var ta = document.forms['salary']['ta'].value;
var pf = document.forms['salary']['pf'].value;
var gross_sal = document.forms['salary']['grosssalary'].value;
window.alert("HI"+gross_sal);
var net_sal = document.forms['salary']['netsalary'].value;
Sijax.request('send',[id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%" >
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return send()" >
<label id = "empid">Employee ID</label><br>
<input type = "text" name = "empid" placeholder = "Employee ID" /><br><br>
<label id = "bsalary">Basic Salary</label><br>
<input type = "text" name = "bsalary" placeholder = "Basic salary" /><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for ="hra">House Rent Allowance(HRA)</label>
<p id="hra" name="hra"></p><br>
<label for ="ta">Travel Allowance(TA)</label>
<p id="ta" name="ta"></p><br>
<label for ="da"> Dearness Allowance(DA)</label>
<p id="da" name="da"></p><br>
<label for ="netsalary">Net Salary</label>
<p id="netsalary" name="netsalary"></p><br>
<label for ="pf">Provident Fund(PF)</label>
<p id="pf" name ="pf"></p><br>
<label for ="grosssalary">Gross Salary</label>
<p id="grosssalary" name="grosssalary"></p><br><br>
<input type="submit" value="Upload Salary">
</form>
</div>
</body>
</html>
You can't act with <p> elements like as a form-elements. You may create a respective <input type="hidden"> elements and fill them in payroll(), or get values by .innerHtml on paragraphs.
P.S. You have actually a TypeError exception, calling undeclared form elements like document.forms['salary']['grosssalary'] and so on.
okay, quick fix, since you are using python flask library Sijax for ajax and therefore jQuery, you can alter your javascript send function like this:
function send(e){
e.preventDefault(); //it is as good as returning
//false from the function in all cases
var id = document.forms['salary']['empid'].value;
...
}
and change your onsubmit handler declaration like this:
<form id="salary" name="salary" style="margin-top: 2%" method="post"
onsubmit="return send(event)" >
please note that when you stop the event chain propagation, you will have to do a manual submission of the form.
So, you can modify your send function to do .preventDefault based on your custom criterias, otherwise, let the form submit
Your code actually works, if you're running this code as a snippet here in stack overflow, Form submission is actually blocked by default. Try running your code in codepen. I tried it and it's actually working.
http://codepen.io/jhonix22/pen/VPZagb
Check this out. It is nowhere close to a perfect solution but I think it helps. You can not access the paragraphs as if you would the form input elements. Im not entirely sure what Sijax thing is. I believe it is just a normal AJAX HTTP thing with some sort of CSRF security filters.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>hr page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript"
src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript">
{
{
g.sijax.get_js() | safe
}
}</script>
<link rel="stylesheet" href="{{url_for('static', filename='styles/signupcss.css')}}">
<script type="text/javascript">
function payroll() {
var basic = document.forms["salary"]["bsalary"].value;
var empid = document.forms["salary"]["empid"].value;
var ta, hra, da, pf, netsalary, grosssalary;
if (empid == "" || basic == "") {
alert("Employee ID and Salary details must be filled out");
return false;
}
if (isNaN(basic)) {
alert("Salary must be in Numbers");
return false;
}
hra = basic * 40 / 100;
da = basic * 15 / 100;
pf = basic * 12 / 100;
basic = parseInt(basic);
hra = parseInt(hra);
da = parseInt(da);
grosssalary = basic + hra + da;
ta = basic * 6.2 / 100;
netsalary = grosssalary - ta;
document.getElementById("hra").innerHTML = hra;
document.getElementById("ta").innerHTML = ta;
document.getElementById("da").innerHTML = da;
document.getElementById("netsalary").innerHTML = netsalary;
document.getElementById("pf").innerHTML = pf;
document.getElementById("grosssalary").innerHTML = grosssalary;
window.alert("HI" + grosssalary);
return true;
}
function send() {
var id = document.forms['salary']['empid'].value;
var basic = document.forms['salary']['bsalary'].value;
var hra = document.getElementById('hra').innerHTML;
var da = document.getElementById('da').innerHTML;
var ta = document.getElementById('ta').innerHTML;
var pf = document.getElementById('pf').innerHTML;
var gross_sal = document.getElementById('grosssalary').innerHTML;
window.alert("HI" + gross_sal);
var net_sal = document.getElementById('netsalary').innerHTML;
// I think you are missing something here.
Sijax.request('send', [id, basic, hra, ta, da, pf, gross_sal, net_sal]);
}
</script>
</head>
<body style="font-family:Lato">
<div style="padding-left:5%;padding-top:0.2%;height:1%;width:100%;background-color:#11557c">
<h2>Welcome to HR Department</h2><br>
</div>
<div style="margin-left:15%">
<h2>Name</h2>
<form id="salary" name="salary" style="margin-top: 2%" method="post" onsubmit="return false">
<label id="empid">Employee ID</label><br>
<input type="text" name="empid" placeholder="Employee ID"/><br><br>
<label id="bsalary">Basic Salary</label><br>
<input type="text" name="bsalary" placeholder="Basic salary"/><br><br>
<input type="button" value="Calculate" onclick="return payroll()"><br><br>
<label for="hra">House Rent Allowance(HRA)</label><br>
<p id="hra" readonly name="hra"></p>
<label for="ta">Travel Allowance(TA)</label><br>
<p id="ta" readonly name="ta"></p>
<label for="da"> Dearness Allowance(DA)</label><br>
<p id="da" readonly name="da"></p>
<label for="netsalary">Net Salary</label><br>
<p id="netsalary" readonly name="netsalary"></p>
<label for="pf">Provident Fund(PF)</label><br>
<p id="pf" readonly name="pf"></p>
<label for="grosssalary">Gross Salary</label><br>
<p id="grosssalary" readonly name="grosssalary"></p><br>
<input type="button" onclick="send()" value="Upload Salary">
</form>
</div>
</body>
</html>

how to not submit a form in js

I want to not submit the form if the inputs are empty, here is my code:
<html>
<head>
<title>
The X/O Game
</title>
<script type="text/javascript">
var check = function () {
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x==""&&o=="")){
alert("fill the form!");
return false;
}
return true;
};
$('#formm').submit(function(e){
var shouldSubmit = check();
if (!shouldSubmit) {
e.preventDefault();
}
});
$('#emotion input:radio').addClass('input_hidden');
$('#emotion label').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<body>
<div>
Please enter your name & choose your character before start playing:
</div>
<div>
<form method=post action=game.php name="formm">
Name:<br>
<input type=text name=player id=p>
</div>
<div>
Character:<br>
<input
type="radio" name="emotion" value="xChar"
id="x" class="input-hidden" />
<label for="x">
<img src="images/x.png " />
</label>
<input
type="radio" name="emotion" value="oChar"
id="o" class="input-hidden" />
<label for="o">
<img src="images/o.png" />
</label>
</div>
<div>
<input type=submit value=Play>
</form>
</div>
</body>
</html>
$('#formm').submit(function(){
return f;
});
this function is called when the user clicks on the submit button.
the form is subbmited even though the inputs are empty, where is the wrong?
f is defined when you call check(), they will not magically update. Do the checks inside the submit function.
You'd better use HTML5 required attribute here:
<form>
<input type="text" name="x" required>
<input type="submit">
</form>
If you want more complex validation, you should have a look at html5rocks.com. The form validation should move from Javascript to HTML now (or in the near future).
But if you want to do it your way, do as epascarello suggests here:
$('#formm').submit(function(){
check();
return f;
});
Try this:
$('#yoursubmitbtnid').click(function(){
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x=="" && o=="")){
alert("fill the form!");
return false;
}
});
You need to run the check function in the submit handler to determine whether or not the submit should be allowed.
var check = function () {
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x==""&&o=="")){
alert("fill the form!");
return false;
}
return true;
};
$('#formm').submit(function(e){
var shouldSubmit = check();
if (!shouldSubmit) {
e.preventDefault();
}
});
You may want to look into using a validation plugin (such as this) if you plan on doing any extensive client side validation.
You need to call the check function when the form is being submitted
$('#formm').submit(function(){
return check();
});
If the check function returns false then the form should not submit.

How to resolve this conflict with jQuery

Can anyone please help me resolve this conflict with my javascript validation?
The form does not submit. But if I remove onsubmit="return btnSubmitPD_OnClick() it redirect the form correctly. But of course I need that function.
Here's my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#Submit').click(function() {
var emailVal = $('#email').val();
$.post('checkemail.php', {'email' : emailVal}, function(data) {
if(data=='exist') {
alert('in'); return false;
}else{
$('#form1').submit();
}
});
});});
</script>
<script type="text/javascript">
function appIsEmail(str){
var at="#";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (str.indexOf(at)==-1) return false;
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
if (str.indexOf(at,(lat+1))!=-1) return false;
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
if (str.indexOf(dot,(lat+2))==-1) return false;
if (str.indexOf(" ")!=-1) return false;
return true;
}
function btnSubmitPD_OnClick(){
frmReg = document.getElementById("form1");
if (!appIsEmail(frmReg.email.value)){
alert("Please enter a valid email address!");
frmReg.email.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php" onsubmit="return btnSubmitPD_OnClick()">
<p>
<input type="text" name="email" id="email" />
</p>
<p>
<input type="button" name="Submit" id="Submit" value="Submit" />
</p>
</form>
</body>
</html>
Several Things:
It is better to bind a submit event to your form, rather than a click event on your submit button, this is to cater for cases where users press enter on the email text field:
$('#form1').submit(function() { // change from $('#Submit').click
Then inside the new submit handler, you call call the email validation method:
var emailVal = $('#email').val();
if(btnSubmitPD_OnClick() === false) return false;
Then, to avoid infinite submit loop, you need to change:
else{
$('#form1').submit();
}
to
else{
$('#form1')[0].submit(); // native submit on form element
}
Or as mplungjan noted in his comment, simply change your
<input type="button" name="Submit" id="Submit" value="Submit" />
To use type="submit"
<input type="submit" name="Submit" id="Submit" value="Submit" />
And add
if(btnSubmitPD_OnClick() === false) return false;
Before your call to $.post

alert box not working in jsp

I added a stylish alert box to my page, resource is here . But problem is after clicking ok, confirmsubmit.jsp is not opening. Also in that alert cancel button is not appearing why?
javascript
<form action="confirmsubmit.jsp" method="POST">
<script type="text/javascript">
<!--
function confirmation() {
var answer = csscody.alert("Confirm submit?")// added csscody here for alert but after clicking ok nothing happens
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;// here cancel button is not coming
}
}
//-->
</script>
</form>
html
<input type="text" name="textboxname"/>
<input type="submit" onclick="return confirmation()"/>
</form>
UPDATE
View below code ,it uses button instead of link
<form action="confirmsubmit.jsp" method="POST">
<script type="text/javascript">
$().ready(function() {
$('#btn_submit').click(function(e) {
e.preventDefault();
var that = this;
var text = "si o no compa?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
window.location = "confirmsubmit.jsp";
}
else {
return false;
}
}
})
});
});
</script>
<input type="text" name="textboxname"/>
<input type="submit" id="btn_submit" onclick="return confirmation()"/>
</form>
You willl have to use confirm instead of alert which will giv eyou both ok and cancel buttons which return true and false respectively. And also take off return from onclick
HTML
<form action = "confirmsubmit.jsp" method = "POST">
<input type = "text" name = "textboxname" />
<input type = "submit" onclick = "confirmation();" />
</form>
Javascript
function confirmation() {
var answer = confirm("Confirm submit?");
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;
}
}

Categories

Resources