I am trying to get submit event triggered for my form and for some reason it is not being activated...
I have added a button to the form of type submit and have a script at the end of the body that references the javascript functions related to the form...
Any ideas??
html
{% extends "layout.html" %}
{% block title %}Upload{% endblock %}
{% block body %}
<div class="container">
<form action="/upload" id="upload-form" method="POST" enctype="multipart/form-data"></form>
<div class="form-group">
<h1>Upload</h1>
<p>Use this form to upload a json file.</p>
</div>
<div class="form-row">
<div class="form-group">
<label for="file-input">JSON file</label>
<input type="file" accept=".json" class="form-control-file" id="file-input" />
</div>
</div>
<div class="form-row">
<pre id="file-contents"></pre>
</div>
<button id="clear-button" type="reset" class="btn btn-primary" disabled="true">Clear</button>
<button id="submit-button" type="submit" class="btn btn-primary" disabled="true">Submit</button>
</form>
</div>
<script src="/static/js/script.js"></script>
{% endblock %}
script.js
/**
* Event handler for form submission
*/
document.querySelector("#upload-form").addEventListener('submit', async event => {
console.log("FORM SUBMIT HANDLER");
event.preventDefault();
const formData = new FormData(event.target);
const fileString = formData.get('file-contents');
const payload = JSON.stringify({
file: fileString
});
console.log("SENDING : " + payload);
const response = await sendFile(payload);
console.log(response);
});
You're having an extra misplaced </form> closing tag immediately following the opening tag for your form. Just remove it and it should work fine.
Related
In my Django/Python application I have fields which are necessary or not, depending on what is selected in previous fields. Thats why those are not mandatory by default. I would like to run a script which would raise an error on the chosen field, depending on the selection. I would like to do that when 'Submit' button is pressed, via script.
My html code:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" novalidate enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Report</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<script>
$("#submit").click(function () {
if (document.getElementById('id_res_person_1').value == '') {
HERE I WOULD RAISE AN ERROR ON THAT FIELD
}
});
</script>
You need to call a function when form is submitted, make your validation and if all good submit to the view
Here is an example:
JS
function validate(url) {
// do your validation
if(allIsOk){
// get the form
my_form.submit();
}
}
On Submit or link
<fom onsubmit="validate()">
Attached code below. I have a submit button that uses a form method POST, and then it's supposed to run the javascript animation, though it kicks me to the next page before it gets the chance to run it.
Is there a way I can add a delay to the submission such that the animation is completed first? In this code, it doesn't even get a chance to run the javascript.
<div class="container">
<div class="pt-5 text-white">
<link rel="stylesheet" href="css/postQuestion.css">
<br>
<br>
<br>
<br>
<h1>Post a question</h1>
<br>
<form method="POST" action="{{ route("post_post") }}">
#csrf
{{-- Title box --}}
<div class="none" style="margin:0 auto;">
<input class="search" name="title" type="text" id="search" placeholder="Title" required/>
</div>
<br>
<div class="none">
{{-- Question box --}}
<textarea required name="content" class="search2" type="text" id="search" placeholder='Explain your question here.
Protip: add your code as <code> YOUR CODE HERE </code> to format correctly.'></textarea>
</div>
<br/>
<div class="dropdownTag">
<select name="label_id" class="dropdownTag-select" required>
<option value="-1">Select Tag</option>
#foreach(\Illuminate\Support\Facades\DB::table("tags")->orderBy('name', 'asc')->get() as $tag)
<option value="{{ $tag->id }}">{{ $tag->name }}</option>
#endforeach
</select>
</div>
<br/>
<div class="container">
<button id="button" type="submit"></button>
<form submit="return function();">
</div>
</form>
</div>
<script>
$(function () {
$("#button").click(function () {
$("#button").addClass("onclic", 250, validate);
});
function validate() {
setTimeout(function () {
$("#button").removeClass("onclic");
$("#button").addClass("validate", 450, callback);
}, 2250);
}
function callback() {
setTimeout(function () {
$("#button").removeClass("validate");
}, 1250);
}
});
</script>
</div>
Using event.preventDefault() you can halt the normal behavior of the form.
After that you can implement whatever you like before manually submitting the form from JS.
If what you need is to wait some time before submitting, you can then use setTimeout().
Then manually submit the form using submit() function.
Vanilla JS
<script>
document.addEventListener('DOMContentLoaded', function () {
document.forms['test_form'].addEventListener('submit', function (e) {
e.preventDefault();
form = this;
// Make a new timeout set to go off in 1000ms (1 second)
setTimeout(function () {
// submit form after timeout
form.submit();
}, 1000);
});
});
</script>
<form name="test_form" method="POST" action="{{ route('post_post') }}">
<label for="test">Test field</label>
<input type="input" name="test"/>
<input type="submit"/>
</form>
document.addEventListener('DOMContentLoaded', function() {
document.forms['test_form'].addEventListener('submit', function(e) {
e.preventDefault();
form = this;
// Make a new timeout set to go off in 1000ms (1 second)
setTimeout(function() {
// submit form after timeout
form.submit();
}, 1000);
});
});
<form name="test_form" method="POST" action="{{ route('post_post') }}">
<label for="test">Test field</label>
<input type="input" name="test" />
<input type="submit" />
</form>
If you need to use the "submit", then you can simply hide the submit button itself, and hang the listener on the button that will call its animations, and then, when you need it, submit.
...
<div class="container">
<button id="button" type="button"></button>
<input id="submit" type="submit" hidden />
<form submit="return function();">
</div>
...
...
$("#button").click(function (event) {
event.preventDefault();
$("#button").addClass("onclic", 250, validate);
...
$("#submit").click();
});
...
It is also possible without creating a hidden input through the form submission. I think this option is better.
...
<form id="someform" method="POST" action="{{ route("post_post") }}">
...
<div class="container">
<button id="button" type="button"></button>
<form submit="return function();">
</div>
...
...
$("#button").click(function (event) {
event.preventDefault();
$("#button").addClass("onclic", 250, validate);
...
$("#someform").submit();
});
...
so ive an HTML page that have multiple generated forms:
{% for row in data %}
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_{{ row[0][1] }}" value="{{ row[0][1] }}"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>
</button>
</form>
{% endfor %}
row[0][1] contains the id of the row.
Im trying to send ajax requests from every single one of them, but i get the same ID of the frist row from every row.
This is the Javascript
$(document).ready(function() { $(".aggiorna_app").click(function(event) {
//prevent submit
event.preventDefault(); //Thx #alex
//do things on submit
$.ajax({
data : {
tipo_richiesta : "inserisci_intervento",
id : $('#id_pratica').val(),
data_int : $('#data_int').val(),
ora_int : $('#ora_int').val()
},
type: "POST",
url: "/aggiorna_pratica",
beforeSend: function(){
//Before send data
},
success: function(data){
console.log(data);
}
});
});
});
I know im a newbie but i could really use some help
Here is a working example to test your click event. The click event is on .aggoriorna_app buttons inside each form, but the id being passed into the ajax call looks to be grabbing the .val() every time, e.g, $('#id_pratica').val(). You'll see in my example that when a button is clicked, find the nearest input value and set the ajax id to that value. I assume that's what you need.
$(document).ready(function() {
$(".aggiorna_app").click(function(event) {
//prevent submit
event.preventDefault(); //Thx #alex
var id = $(this).parent().find('input').val();
alert(id);
});
});
form {
margin-bottom: 3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_1" value="input_1"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>CLICK ME
</button>
</form>
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_2" value="input_2"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>CLICK ME
</button>
</form>
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_3" value="input_3"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>CLICK ME
</button>
</form>
</div>
Hi have very simple html with form, but submitting doesn't work.
I checked multiple solutions I found on stackoverflow, but still doesn't work.
<form class="form-horizontal well" method="post" id="upload_excel" name="upload_excel" enctype="multipart/form-data">
<fieldset>
<div class="control-group">
<div class="control-label">
<label>Excel File:</label>
</div>
<div class="controls">
<input type="file" name="file" id="file" class="input-large">
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="btn" name="Import" class="btn btn-primary button-loading" data-loading-text="Loading...">Upload</input>
</div>
</div>
</fieldset>
And JavaScript in the same file:
<script type="text/javascript" language="javascript" >
$(document).ready(function (e) {
$('#btn').on('submit',(function(e) {
alert('test');
}));
});
</script>
When I click on btn shouldn't the form be submitted and alert window occurs?
Try putting the on submit function on the form instead of on the button.
<script type="text/javascript" language="javascript" >
$(document).ready(function (e) {
$('#upload_excel').on('submit',(function(e) {
alert('test');
}));
});
</script>
What about the "action" attribute for the "form" element?
Basiclally you have to submit form so you should have the id of form in the onsubmit block and not input submit button.
<script type="text/javascript" language="javascript" >
$(document).ready(function (e) {
$('#upload_excel').on('submit',(function(e) {
alert('test');
}));
});
</script>
And Yes You Need to have the action attribute to make a post or get request to the server
Hope This Helps.
You have bad Jquery selector for .on('submit')
You can also use e.preventDefault() to prevent the form from actually being submitted.
Moreover, the <input> tag has no </input> closing tag, use value="Upload" instead for a submit or a button
$(document).ready(function (e) {
$('#upload_excel').on('submit',(function(e) {
e.preventDefault();
alert('test');
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal well" method="post" id="upload_excel" name="upload_excel" enctype="multipart/form-data">
<fieldset>
<div class="control-group">
<div class="control-label">
<label>Excel File:</label>
</div>
<div class="controls">
<input type="file" name="file" id="file" class="input-large">
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" id="btn" name="Import" class="btn btn-primary button-loading" data-loading-text="Loading..." value="Upload"/>
</div>
</div>
</fieldset>
You haven't defined the "action" parameter in tag. So, when you press Submit, you fire a POST call without having specified the URL to be called.
A simple example is:
<form enctype="multipart/form-data" action="__URL__" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Where URL is a page PHP or whatever else you have exposed for receiving this call. Another example is here.
First of all I alert a message showing that the submit button is pressed, using this instruction:
$('#btn').on('click',(function(e) {alert("Submitted");}));
After that I'm ensuring that the form is submitted using the jQuery
function .submit():
$( "#upload_excel" ).submit();
Finally, here is the entire script:
<script type="text/javascript" language="javascript" >
$(document).ready(function (e) {
$('#btn').on('click',(function(e) {
alert("Submitted");
$( "#upload_excel" ).submit();
}));
});
</script>
My answer is based on the jQuery documentation, & a Stackoverflow answer.
I have been trying to create a submit form that both makes getJSON call to display the response on html template and submits input. But I can only either submit the input or display response received from getJSON call. I have tried removing preventDefault method and adding it to my function but it is still not working.
Thank you in advance for any suggestions!
<form method="post" id="form">
<div>
<input type="text" name="newpost" style="width:300px;" placeholder="post here...">
{% if user %}
<input type="hidden" name="user_id" value="{{ user.key.id() }}">
<input id="inputButton" type="submit" value="Done">
<div id="jsonInfo"></div>
<script>
$(document).ready(function (){
$('#inputButton').click(function (e) {
var URL = 'URLEXAMPLE';
$.getJSON(URL, function(data){
for (var i = 0; i < data.length; i++){
var info = data[i].content;
$("#jsonInfo").append(info);
};
});
e.preventDefault();
});
});
</script>
{% else %}
<input type="button" class="button_active" onclick="location.href='/login'" value="Done">
{% endif %}
</div>
</form>
After the for do a
$('#form').submit(); to submit the form, e.preventDefault(); is currently blocking the default form submission so you can send the ajax request