submiting form on div click with js - forms

I have a div element and I want that when I click on it i submit a form which is hidden.
div code
<div class="a15 training-exercise">
some text
<form accept-charset="UTF-8" action="/trainings/1/training_exercises/5" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put"></div>
<input id="training_exercise_done" name="training_exercise[done]" type="text" value="false">
<input name="commit" type="submit" value="subit">
</form>
</div>
coffescript
$ ->
$('.training-exercise').click ->
if $(this).hasClass('done')
$(this).removeClass('done')
$(this).find('input:text').val(false)
$(this).closest("form").submit()
else
$(this).addClass('done')
$(this).find('input:text').val(true)
$(this).closest('form').submit()
corresponding JS code
$(function() {
return $('.training-exercise').click(function() {
if ($(this).hasClass('done')) {
$(this).removeClass('done');
$(this).find('input:text').val(false);
return $(this).closest("form").submit;
} else {
$(this).addClass('done');
$(this).find('input:text').val(true);
return $(this).closest('form').submit;
}
});
});
i didn't put checkbox for true and false because f.checkbox gave me some strange results
The problem here is:
1) Everything is happening except form submitting
2) form has visibility: hidden; and it is hidden, but there is empty space where the form is, I want that it looks like there is nothing there

For 1st problem, try
$(function() {
$('.training-exercise').click(function() {
var element = $(this);
if (element.hasClass('done')) {
element.removeClass('done');
element.find('input:text').val(false);
element.closest('form').submit(); //<-- brackets here.
} else {
element.addClass('done');
element.find('input:text').val(true);
element.closest('form').submit();
}
});
});
For 2nd problem use display:none; instead of visibility:hidden.

It seems that form selecting didn't work (although it work when I tried from console)
The solution that works is:
$(this).find('input:submit').submit()

Related

Why Is my script freezing up when I hit enter?

The majority of the Add-on is good but whenever I hit enter (which is, in my opinion, the most common way to submit a form, for example, a login form), but all it does is blank out.
I've tried linking the script with a onkeydown like so:
<div onkeydown="handle(event)">blagh blagh blagh</div>
but I still get the same results:
<html>
<form id='myForm' style="font-family:Georgia;">
<table>
<tr><td><h2>Enter your Password</h2></td></tr>
<tr><td><p>DO NOT HIT ENTER ON YOUR KEYBOARD!!!!!</p></td></tr>
<tr><td><input name='password' type='password' value="" onkeypress="handle(event)"></td></tr>
<tr><td><div id="submitbuttcontainer"><img id="submitloader" style="display:none;" src='https://lh6.googleusercontent.com/-S87nMBe6KWE/TuB9dR48F0I/AAAAAAAAByQ/0Z96LirzDqg/s27/load.gif' /><input id="submitbutt" type='button' onclick='showWorking();google.script.run.withSuccessHandler(onSuccess).decodeForRequest(document.getElementById("myForm"));' name="Submit" value="Submit"></div></td></tr>
</table>
</form>
<script>
function onSuccess(obj) {
document.getElementById('submitbutt').style.display="block";
document.getElementById('submitloader').style.display="none";
if(obj.status == 'success') {
google.script.host.closeDialog();
browser.msgbox('Access Granted', browser.buttons.OK)
}
else {
browser.msgbox('ALERT!!','!OOF!','Incorrect Password. Please retry', browser.buttons.OK);
}
}
function showWorking() {
document.getElementById('submitbutt').style.display="none";
document.getElementById('submitloader').style.display="block";
}
function handle(e){
if(e.keyCode === 13)
document.getElementById('submitbuttcontainer').click();
}
</script>
</html>
All I'm trying to do is get the form to submit when I hit enter and not blank out. I always hit enter to submit a form but in this case all it does is blank out the form and all I have is whiteness.
Here's the link for the complete source code (don't know if this will work because I'm in a school district):
https://script.google.com/a/bcsdschools.net/d/1_YUx4ZP3qEWVcFMc-MvfEYX2S34r7-b4M0iRlE_JQa81T3ZubN5OeISa/edit)
Problem
Hitting enter key results in form submission (which is explicitly forbidden in Apps Script due to its client-to-server communication implementation).
Solution 1 - handle inputs individually
Add preventDefault() to a keydown event if key is enter (btw, keypress event is deprecated, see reference on MDN, use the keydown / keyup instead):
var ENTER_CODE = 13;
function handle(e) {
if(e.keyCode === ENTER_CODE) {
e.preventDefault();
document.getElementById('submitbuttcontainer').click();
}
}
Solution 2 - handle form submit
You can listen for a submit event on your form instead and invoke preventDefault() as the only statement in event handler or handle form submission at the same time if you expect form to be submitted on enter key hit:
//assumption: form is initiated elsewhere in code;
form.addEventListener('submit', (event) => {
event.preventDefault();
//handle submission;
});
You can also prevent all forms from being submitted to make the setup flexible:
(() => {
const { forms } = document;
Object.values(forms).forEach(
form => form.addEventListener("submit", (e) => e.preventDefault())
);
})();
Or, alternatively, use event delegation and register one listener on the document since the event bubbles up:
document.addEventListener("submit", (e) => e.preventDefault());
Suggestion
Please, use addEventListener instead of on[event name here] attributes. This way is much more flexible and has the benefit of being concise and easy for others to read.
References
Handling forms in Apps Script guide
Why use addEventListener? MDN reference
I wanted to try to give you a complete answer, but I have to admit that I may know less about event handlers than you. But this seems to work for me.
aq4.html:
<html>
<head>
<script>
window.onload=function() {
preventFormSubmit1();
}
function preventFormSubmit1() {
console.log('preventFormSubmit1');
var form=document.forms['myForm'];
form.addEventListener('submit',function(e) {
e.preventDefault();
});
}
function handleFormSubmit(formObject) {
console.log('handleFormSubmit');
var first=document.forms['myForm']['first'].value;
var last=document.forms['myForm']['last'].value
var sheet=document.forms['myForm']['sheet'].value;
console.log('%s,%s,%s',first,last,sheet);
if(first.length>0 && last.length>0 && sheet.length>0) {
google.script.run
.withSuccessHandler(function(msg){
var div=document.getElementById('output');
div.innerHTML=msg;
var inputs=document.querySelectorAll('input[type=text]');
inputs[0].focus();
for(var i=0;i<inputs.length;i++) {
inputs[i].value='';
}
})
.processForm(formObject);
}else{
alert("Invalid or Incomplete Data");
}
}
console.log("MyCode");
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="first" /> First<br />
<input type="text" name="last" /> Last<br />
<select name="sheet">
<option value="Sheet1">Sheet1</option>
<option value="Sheet2">Sheet2</option>
</select> Sheet<br />
<input id="sub" type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
aq1.gs:
function processForm(formObject) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(formObject.sheet);
sh.appendRow([formObject.first,formObject.last]);
return Utilities.formatString('First: %s<br />Last: %s<br />Sheet: %s', formObject.first,formObject.last,formObject.sheet);
}
function runOne() {//This loads the dialog
var userInterface=HtmlService.createHtmlOutputFromFile('aq4').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Form Example")
}

angular 2, validate form if at least one input is typed

I'm quite new to Angular, and I've already searched the web, without finding a correct solution for my situation.
I have a dynamic form created by a *ngFor. I need to disabled the submit button if the inputs are all empty and show the alert div; but I need to enable the submit if at least one of those forms contains something different from ''.
Here is my html code
<form class="form-inline" #form="ngForm">
<div class="form-group" *ngFor="let meta of state.metaById; let i = index" style="margin: 5px">
<label>{{meta.nome}}</label>
<input type="text" class="form-control" #nome (blur)="inputInArray(nome.value, i);">
</div>
<button type="button" class="btn btn-primary" (click)="getCustomUnitaDocumentaliRow(this.param)" [disabled]="fieldNotCompiled">invia</button>
</form>
<div class="alert-notification" [hidden]="!fieldNotCompiled">
<div class="alert alert-danger">
<strong>Va compilato almeno un campo.</strong>
</div>
</div>
and here is my Typescript code
inputInArray(nome: string, indice) {
if (this.state.controlloMetaId = true) {
this.state.metadatoForm[indice] = nome;
}
// this.fieldNotCompiled = false;
for (const i in this.state.metaById) {
console.log(this.state.metadatoForm);
if (isUndefined(this.state.metadatoForm[i]) || this.state.metadatoForm[i] === '') {
this.fieldNotCompiled = true && this.fieldNotCompiled;
} else {
this.fieldNotCompiled = false && this.fieldNotCompiled;
}
console.log(this.fieldNotCompiled);
}
With this code I can check the first time a user type something in one input, but it fails if it empty one of them (or all of them)
Thanks for your time
UPDATE
Check if any input got a change that is different from empty or space, just by doing:
<input ... #nome (input)="fieldNotCompiled = !nome.value.trim()" ....>
DEMO
You can set a listener to the form changes:
#ViewChild('form') myForm: NgForm;
....
ngOnInit() {
this.myForm.valueChanges.subscribe((value: any) => {
console.log("One of the inputs has changed");
});
}

Form gets invalid after form.reset() - Angular2

I have a template based form in my Angular2 app for user registration. There, I am passing the form instance to the Submit function and I reset the from once the async call to the server is done.
Following are some important part from the form.
<form class="form-horizontal" #f="ngForm" novalidate (ngSubmit)="onSignUpFormSubmit(f.value, f.valid, newUserCreateForm, $event)" #newUserCreateForm="ngForm">
<div class="form-group">
<label class="control-label col-sm-3" for="first-name">First Name:</label>
<div class="col-sm-9">
<input type="text" class="form-control" placeholder="Your First Name" name="firstName" [(ngModel)]="_userCreateForm.firstName"
#firstName="ngModel" required>
<small [hidden]="firstName.valid || (firstName.pristine && !f.submitted)" class="text-danger">
First Name is required !
</small>
</div>
</div>
.......
.......
<div class="form-group">
<div class="col-sm-offset-3 col-sm-12">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-link">Reset</button>
</div>
</div>
</form>
In my component file, I have written following function.
onSignUpFormSubmit(model: UserCreateForm, isValid: boolean, form: FormGroup, event:Event) {
event.preventDefault();
if (isValid) {
this._userEmail = model.email;
this._authService.signUp(this._userCreateForm).subscribe(
res => {
console.log("In component res status = "+res.status);
if(res.status == 201){
//user creation sucess, Go home or Login
console.log("res status = 201");
this._status = 201;
}else if(res.status == 409){
//there is a user for given email. conflict, Try again with a different email or reset password if you cannot remember
this._status = 409;
}else{
//some thing has gone wrong, pls try again
this._serverError = true;
console.log("status code in server error = "+res.status);
}
form.reset();
alert("async call done");
}
);
}
}
If I submit an empty form, I get all validations working correctly. But, when I submit a valid form, Once the form submission and the async call to the server is done, I get all the fields of the form invalid again.
See the following screen captures.
I cannot understand why this is happening. If I comment out form.reset(), I do not get the issue. But form contains old data i submitted.
How can I fix this issue?
I solved this By adding these lines:
function Submit(){
....
....
// after submit to db
// reset the form
this.userForm.reset();
// reset the errors of all the controls
for (let name in this.userForm.controls) {
this.userForm.controls[name].setErrors(null);
}
}
You can just initialize a new model to the property the form is bound to and set submitted = false like:
public onSignUpFormSubmit() {
...
this.submitted = false;
this._userCreateForm = new UserCreateForm();
}
You need to change the button type submit to button as following.
<div class="form-group">
<div class="col-sm-offset-3 col-sm-12">
<button type="button" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-link">Reset</button>
</div>
</div>
Reseting the form in simple javascript is the solution for now.
var form : HTMLFormElement =
<HTMLFormElement>document.getElementById('id');
form.reset();
this is how finally I had achieved this. I am using Angular5.
I have created a form group named ="firstFormGrop".
If you are not using form groups you can name the form as follow:
<form #myNgForm="ngForm">
In the html doc:
<form [formGroup]="firstFormGroup">
<button mat-button (click)='$event.preventDefault();this.clearForm();'>
<span class="font-medium">Create New</span>
</button>
</form>
In the .ts file:
this.model = new MyModel();
this.firstFormGroup.reset();
if you where using #myNgForm="ngForm then use instead:
myNgForm.reset();
// or this.myNgForm.reset()
This is a very common issue that after clicking the reset button we created the validators are not reset to its initial state, and it looks ugly.
To avoid that we have two options,the button is outside the form, or we prevent the submission when the button is tagged inside the form.
To prevent this default behaviour we need to call $event.preventDefault() before whatever method we are choosing to clear the form.
$event.preventDefault() is the key point.
The solution:
TEMPLATE:
<form
action=""
[formGroup]="representativeForm"
(submit)="register(myform)"
#myform="ngForm"
>
*ngIf="registrationForm.get('companyName').errors?.required && myform.submitted"
COMPONENT:
register(form) {
form.submitted = false;
}
Try changing the button type from "submit" to "button", e.g. :
<button type="button">Submit</button>
And move the submit method to click event of the button. Worked for me!

Date picker empty error

I got a form that posts some value to another page. I want alert for datepicker inputs when i post form if they are empty. I have been trying to solve it but couldn't. It is simple but my brain just stopped i think. Code is below.
http://i.stack.imgur.com/Ee95P.png
This is the link of screenshot of my form. Maybe this can help you.
<form id="form-2" class="form-3" method="POST" action="rezervasyon-aşama-2" >
<label style="margin:2px 70px; font-size:16px;" >Rezervasyon Formu</label><br>
<div style="padding:5px 5px;">
Check-in Tarihi:
<input id="datepicker-example7-start" type="text" name='tarih1' >
</script>
</div>
<div style="padding:5px 5px;">
Check-out Tarihi:
<input id="datepicker-example7-end" type="text" name='tarih2' >
</div>
<input TYPE="submit" class="button" NAME="Submit" VALUE="Rezervasyon Yap" >
</form>
when i click input file, the datepicker shows up. So i want a alert if i submit empty. Sorry for my English :) Thanks for helps.
Changed the attribute from ID to NAME -- it was an oversight on my part.
$(document).ready(function () {
$('form').submit(function (e) {
$('input[name^="tarih"]').each(function () {
if ($(this).val().length === 0) {
alert("Your alert here"); //Whatever error message here.
e.preventDefault();
return false;
}
});
});
});
Fiddle:
http://jsfiddle.net/6tp9P/3/

Checking if text area is blank prior to form submission?

So I wrote this code so that every time someone clicks the submit button, a javascript
function, called check, will see if the text area is empty. If it is not, then the form will be submitted.
This is my code. Why isn't it working?
<form method=post name='form_post' id='form_post' action='SUBMITIT.PHP'>
<textarea id=message name=message class=post onfocus=this.className='post_focus';
placeholder='Share your thoughts' maxlength=500></textarea>
<br>
<button onclick='check()' id=button name=button>Post</button>
</form>
<script type="text/javascript">
function check()
{
if(!document.textArea.message.value=="")
{
document.forms["form_post"].submit();
}
}
</script>
Thanks!
EDIT: I finally got it to work. Here's a template if you are having a similar problem.
<!--The form-->
<form action="mypage.php" method="post" name="myForm" id="myForm">
<textarea name=myTextArea id=myTextArea>
</textarea>
</form>
<br>
<button onclick='check()'>
Post
</button>
<!--The script that checks-->
<script type="text/javascript">
function check(){
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
var textAreaValue=document.getElementById('myTextArea').value;
var trimmedTextAreaValue=textAreaValue.trim();
if(trimmedTextAreaValue!="") {
document.forms["myForm"].submit();
}
}
</script>
The following woks, and it also wipes unnecessary spaces, the form will only submit when given a character
<form action="yourpage.php" method="post" onsubmit="return check(this)">
<textarea id="message"></textarea>
<input type="submit" value="Post" />
</form>
<script>
function check(form){
if (form.message.value.trim() == ""){
return false
}
}
</script>
This is the most simple way to do this, and the advised one.
You could simply add "required" to the textarea field in HTML.
Note: Although the question is quite old, I am adding the answer for the future references.