Simple form submit doesn't work - javascript

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.

Related

How do I make sure my javascript animation runs before submit button is done?

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();
});
...

Replace div after form submit

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$("#p").replaceWith($("#p1"));
});
});
</script>
</head>
<body>
<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>
<form action="" method="get">
<input type="submit" id="submit" name="submit" value="Search"/>
</form>
</body>
</html>
This code works fine until I put form action.. When I keep that submit in a form, this code does not work. How can i replace that div after form submit. Thanks.
You can try this one. Hope it helps!
$(document).ready(function(){
$("#submit").click(function(event){
$("#p").replaceWith($("#p1").text());
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>
<form action="" method="get">
<input type="submit" id="submit" name="submit" value="Search"/>
</form>
you need text method for that .
you were removing entire element before . you need to remove only text value
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$("#p").replaceWith($("#p1").text());
});
});
</script>
</head>
<body>
<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>
<input type="submit" id="submit" name="submit" value="Search"/>
</body>
</html>
Specify what to replace it with:
$(this).replaceWith("<div><p>Replacement</p></div>");
Form submission needs to be done using AJAX then only you can achieve this which you want to do.
Otherwise the form will submit and page will refresh which will result to re initialization of script.
As Pooojaaqaa and Rayon mention the when the action attribute is set on the form tag, the form is submitted and the page is reloaded (even if action="#"). To catch this action you need to catch the form's submit event, not the button's click event. In the submit event handler you need to call preventDefault() on the event object passed into the handling function like below.
<form id="frmSearch" action="#" method="get">
<input type="submit" id="submit" name="submit" value="Search"/>
</form>
$("#frmSearch").submit(function(ev){
ev.preventDefault();
$("#p").replaceWith($("#p1").text());
});

Required attribute not working using javascript submit

I make some form different action within different button
<form id="form" method="post" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required>
</form>
<button type="button" class="btn btn-primary" onClick="submitForm('<?php echo base_url('order/add');?>')">Submit</button>
<button type="button" class="btn btn-warning" onClick="submitForm('<?php echo base_url('order/print');?>')">Print</button>
Javascript
function submitForm(action)
{
document.getElementById('form').action = action;
document.getElementById('form').submit(
);
}
Then, my required attribute not working. Did I do something wrong? Let me know if there is other solution.
Thanks,
I can't give you a good explanation but you need the submit buttons inside the form.
So if you would have a button like:
<input type="submit" value="Submit">,
it will trigger the required attribute.
#Remn If you would still stay on your structure with submit inside a function you could trigger yourself the validation like:
if ($("form")[0].checkValidity())
{
$("form").submit()
}
and then do something with inputs that are invalid by passing through each required element ( input is set in code ):
$('form :input[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
In the below case the invalid inputs will be focused one by one.
The whole code is:
$( function () {
$("body").on("click", "#trigger", function() {
if ($("form")[0].checkValidity())
{
$("form").submit()
}
$('form :input[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
});
});
Where #trigger is an id I set on the button to submit, you can make your own functions to achieve your goal I just used on().
I hope it helps!
Please try bellow code. i hope solve your problem.
<html>
<head>
<title>Submit</title>
<script type="text/javascript" language="javascript">
function submitForm(action)
{
document.getElementById('form').action = action;
document.getElementById('form').submit(
);
//alert(document.getElementById('form').action);
}
</script>
</head>
<body>
<form id="form" method="get" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required="required">
<button type="submit" class="btn btn-primary" onclick="return submitForm('<?php echo base_url('order/add');?>');" id="submit">Submit</button>
<button type="submit" class="btn btn-warning" onclick="return submitForm('<?php echo base_url('order/print');?>');" id="print">Print</button>
</form>
</body>
</html>
I have test your code by adding Javascript part in Script tag it is working fine. And i tested it on Chrome Windows 10.
<form id="form" method="post" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required>
</form>
<button type="button" class="btn btn-primary" onClick="submitForm('<?php echo base_url('order/add'); ?>')">Submit</button>
<button type="button" class="btn btn-warning" onClick="submitForm('<?php echo base_url('order/print'); ?>')">Print</button>
<script>
function submitForm(action) {
document.getElementById('form').action = action;
document.getElementById('form').submit();
}
</script>
Using javascript's form.submit() function will cause input validation to be bypassed (according to the HTML specification in point 4 of the form submission algorithm). The only way to trigger HTML input validation is to use a click event on a submit button inside the form, either by the user actually clicking, or in javascript with something like form.querySelector('input[type="submit"]').click().

JQueryMobile form always empty

I'm trying to do a simple JQM AJAX form post to a server - but for some reason, my form input values are always empty. (Even in the DOM inspector)
This is the 2nd page in my HTML - and the only form on the page. The console always prints out "[]"
<div data-role="page" id="login">
<div data-role="content">
<h2>
Login
</h2>
<form id="loginform" data-ajax="false">
<fieldset>
<input name="" id="userId" name="userId" placeholder="login" type="number">
<input name="" id="password" name="password" placeholder="password" type="password">
<input type="button" id="login_submit" data-theme="b" value="Submit">
</fieldset>
</form>
</div>
<script language="JavaScript" >
$(document).on('pagebeforeshow', "#login", function(){
$(document).on('click', '#login_submit', function() {
console.debug($('#loginform').serializeArray());
});
});
</script>
</div>
And the answer is obvious once it's posted into SO.
There's duplicate name attributes on the input fields - note the original issue was probably that the name attributes were set as "" - which would drop them from the form submission.
Try:
$(document).on('submit', '#loginform', function() {
console.debug($('#loginform').serializeArray());
});

How do I auto-submit an upload form when a file is selected?

I have a simple file upload form. How do I make it submit automatically when a file has been selected? I don't want the user to have to click the Submit button.
You can simply call your form's submit method in the onchange event of your file input.
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
};
http://jsfiddle.net/cwvc4/73/
Just tell the file-input to automatically submit the form on any change:
<form action="http://example.com">
<input type="file" onchange="form.submit()" />
</form>
This solution works like this:
onchange makes the input element execute the following script, whenever the value is modified
form references the form, that this input element is part of
submit() causes the form to send all data to the URL, as specified in action
Advantages of this solution:
Works without ids. It makes life easier, if you have several forms in one html page.
Native javascript, no jQuery or similar required.
The code is inside the html-tags. If you inspect the html, you will see it's behavior right away.
Using jQuery:
$('#file').change(function() {
$('#target').submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="target" action="destination.html">
<input type="file" id="file" value="Go" />
</form>
JavaScript with onchange event:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="filename" onchange="javascript:this.form.submit();">
</form>
jQuery
.change() and .submit():
$('#fileInput').change(function() {
$('#myForm').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form action="upload.php" id="myForm">
<input type="file" id="fileInput">
</form>
The shortest solution is
<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" />
<form id="thisForm" enctype='multipart/form-data'>
<input type="file" name="file" id="file">
</form>
<script>
$(document).on('ready', function(){
$('#file').on('change', function(){
$('#thisForm').submit();
});
});
</script>
This is my image upload solution, when user selected the file.
HTML part:
<form enctype="multipart/form-data" id="img_form" method="post">
<input id="img_input" type="file" name="image" accept="image/*">
</form>
JavaScript:
document.getElementById('img_input').onchange = function () {
upload();
};
function upload() {
var upload = document.getElementById('img_input');
var image = upload.files[0];
$.ajax({
url:"/foo/bar/uploadPic",
type: "POST",
data: new FormData($('#img_form')[0]),
contentType:false,
cache: false,
processData:false,
success:function (msg) {}
});
};
If you already using jQuery simple:
<input type="file" onChange="$(this).closest('form').submit()"/>
Try bellow code with jquery :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){
$('#myForm').on('change', "input#MyFile", function (e) {
e.preventDefault();
$("#myForm").submit();
});
});
</script>
<body>
<div id="content">
<form id="myForm" action="action.php" method="POST" enctype="multipart/form-data">
<input type="file" id="MyFile" value="Upload" />
</form>
</div>
</body>
</html>
For those who are using .NET WebForms a full page submit may not be desired. Instead, use the same onchange idea to have javascript click a hidden button (e.g. <asp:Button...) and the hidden button can take of the rest. Make sure you are doing a display: none; on the button and not Visible="false".
HTML
<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>
JAVASCRIPT PURE
<script type="text/javascript">
window.onload = function() {
document.getElementById("xfilename").onchange = function() {
document.getElementById("xtarget").submit();
}
};
</script>
You can put this code to make your code work with just single line of code
<input type="file" onchange="javascript:this.form.submit()">
This will upload the file on server without clicking on submit button
<form action="http://example.com">
<input type="file" onchange="Submit()" />
</form>
<script>
// it will submit form 0 or you have to select particular form
document.getElementsByTagName("form")[0].submit();
</script>
$('#file').change(function() {
$('#target').submit();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="target" action="destination.html">
<input type="file" id="file" value="Go" />
</form>

Categories