Form Submit connected to js event not working - javascript

I have the following code:
<form action="" id="search-form">
<fieldset>
<div class="rowElem">
<input type="text">
<a href="#" onClick="document.getElementById('search-form').submit()">
<div>Search</div>
</a></div>
</fieldset>
</form>
<script>
$(document).ready(function() {
$('#search-form').submit(function(event){
event.preventDefault();
alert("test");
});
});
</script>
When I submit the form I don't see the alert... What am I missing?
Thanks,

You need to remove your obtrusive onclick event and bind to the link instead.
You can't alert AFTER you submit, since that would perform whatever action you give to the form (most likely taking you off the page. If you insisted on doing so, the following would work.
<form action="" id="search-form">
<fieldset>
<div class="rowElem">
<input id="name" type="text"></input>
<a href="#" id="search" >Search</a>
</div>
</fieldset>
</form>
<script>
$(document).ready(function() {
$('#search').bind('click', function () {
// Alert the name BEFORE you do the form post
alert($('#name).val());
$('#search-form').submit(function(event){
});
});
});
</script>
I have a working JSFiddle example here: http://jsfiddle.net/7jqUF/5/
If, instead, you wanted an AJAX solution, you'd want to do something other than a form post, such as an ajax post
<script>
$(document).ready(function() {
$('#search').bind('click', function () {
// Alert the name BEFORE you do the form post
alert($('#name).val());
$.post('/ServerUrl/method', { name: $('#name').val() });
});
});
</script>

Why don't you do something like
<form action="" id="search-form">
<fieldset>
<div class="rowElem">
<input name="query" type="text" /><br />
<a class="search" href="#">Search</a>
</div>
</fieldset>
</form>
and
var form = $('#search-form');
$('.search', form).click(function(event){
event.preventDefault();
var query = $('input[name="query"]', form).val();
alert("test: " + query);
});
Demo: Fiddle
If you want to use the params as part of a ajax request you can do something like
var form = $('#search-form');
$('.search', form).click(function(event){
event.preventDefault();
var params = form.serialize();
alert("test: " + form.serialize());
$.ajax({
url: '...',
data: params,
....
})
});

Please try the following code. After removing the submit code from the $(document).ready function
<a href="#" onclick="document.getElementById('search-form').submit();">

Related

AJAX form only allows one submission?

I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?
How do i accomplish the form and script so I do not have to refresh?
Here is the form:
<form role="form" class="form-horizontal validate" name="create_form" id="create_form">
<div class="form-group">
<label class="col-sm-2 control-label" for="name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
</div>
</div>
<div class="form-group-separator"></div>
<div class="form-group">
<button id="submit_btn" class="btn btn-success">Create</button>
<button type="reset" class="btn btn-white">Reset</button>
</div>
</form>
And here is the AJAX part:
$(document).ready(function(){
$("#submit_btn").on("click", function () {
$.ajax({
type: 'POST',
url: 'data/create.php',
cache: false,
data: $('#create_form').serialize()
})
.done(function(data){
$("#name").val("");
})
.fail(function() {
console.log("ERROR");
});
// Prevent refreshing the whole page page
return false;
});
});
Hoping for help and thanks in advance :-)
use submit instead of click.
$('#submit_btn').on('submit', function(e) {
e.preventDefault();
... //rest of the code
});
I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>

DIV in the form and post them on the same page

<form action="" method="post">
<div id="MG_TextBox" contenteditable="true" name="textBox1" style="width:600px;height:400px; background-color:#ECCBCB;"> Hello</div>
<input type="hidden" name="hiddeninput" id="MH_Hiddeninput" >
<input type="submit" id="MG_Submit" name="submit" value="Submit"/>
</form>
And ajax
<script>
$(function(){
$('#MG_Submit').click(function () {
var MG_Text = $('#MG_TextBox').html();
$('#MG_Hiddeninput').val(MG_Text);
return true;
});
});
</script>
then php
<?
if ($_POST['hiddeninput']) {
print $_POST['hiddeninput'];
}
?>
I would like to have transferred DIV content to HIDDEN INPUT. Subsequently PHP to print them on the same page. ie. action = ""
what am I doing wrong?
Version 2. still not work
<?
if ($_POST['hiddeninput']) { print $_POST['hiddeninput']; }
?>
<html>
<head>
<script>
$(function(){
$('#MG_Form').on("submit", function (e) {
var MG_Text = $('#MG_TextBox').html();
$('#MG_Hiddeninput').val(MG_Text);
e.preventDefault();
});
});
</script>
</head>
<body>
<form action="" method="post" id="MG_Form" enctype="multipart/form-data">
<div id="MG_TextBox" contenteditable="true" name="textBox1" style="width:300px;height:200px; background-color:
#9AB5BF;"> Hello</div>
<input type="hidden" name="hiddeninput" id="MG_Hiddeninput" >
<input type="submit" id="MG_Submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Try this, you don't want the form to submit, you want the AJAX to fire instead. Do this to stop the click from doing its default behaviour - which would submit the form;
<script>
$(function(){
$('form').on("submit", function (e) {
var MG_Text = $('#MG_TextBox').html();
$('#MG_Hiddeninput').val(MG_Text);
e.preventDefault();
});
});
</script>
You may want to add an id to the form, so that the $('form') selector can be more specific. As this might currently break other forms on the page.
for starters, you're trying to select an element that doesn't exist (MG_Hiddeninput). Change to this:
<script>
$(function(){
$('#MG_Submit').click(function () {
var MG_Text = $('#MG_TextBox').html();
$('#MH_Hiddeninput').val(MG_Text);
e.preventDefault();
return true;
});
});
</script>
or change the id of your hidden input to match your selector.
<input type="hidden" name="hiddeninput" id="MG_Hiddeninput" >
also add e.preventDefault() to prevent form from posting. you mention ajax but i don't see any in action here.

Request is being sent to server twice

I am submitting a form to server using following method:
HTML Form
<form class="navbar-search pull-left" onsubmit="return mera()">
<input placeholder="Search" class="search-query span2" name="query" type="text" id="query" style="width:300px">
</form>
Method
<script>
function mera() {
alert('this is something!');
var query = document.getElementById('query').value;
window.location = '../Translation/Search_Query?query=' + query;
return false;
}
</script>
It sends request twice to server on single submission. But shows alert only once for first time. How to fix it ?
You dont need javascript. Simply use GET method
HTML :
<form class="navbar-search pull-left" method="GET" action="../Translation/Search_Query">
<input placeholder="Search" class="search-query span2" name="query" type="text" id="query" style="width:300px">
</form>
When you submit the form, this will become :
http://example.com/Translation/Search_Query?query=query
Hope this makes sense.
Try this
<script>
function mera() {
alert('this is something!');
var query = document.getElementById('query').value;
window.location = '../Translation/Search_Query?query=' + query;
return true;
}
</script>
<form class="navbar-search pull-left" onsubmit="return mera();">
why dont you change you code a bit. only thing is it will post the value instead of get.
<form class="navbar-search pull-left" action="../Translation/Search_Query">
it will submit your value once you submit the form.
Note : you might need to change the action as per your servlet mapping.
UPDATE
<script>
function mera() {
document.getElementById('testForm').submit();
}
</script>
<form id="testForm" class="navbar-search pull-left" onclick="mera();" method="GET" action="../Translation/Search_Query">

javascript Submit multiple forms with one button

In my html I have multiple forms (text inputs, radio buttons, check boxes and select) and one button. I would like to fill all these forms and send values to my php file. For now I am trying to submit values from text input and select but I am stuck at this point.
I have a js submit file:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
And my forms are like this:
SELECT:
<form id ="form1" name="dists" action="solve.php" method="post">
<select id="demo" name="sadzba" onchange="selectElement1(this.value)>
<option value="">-- vyberte oblasť --</option>
</select>
</form>
Text input form + button:
<form id="form2" action="solve.php" method="post">
<input type="text" name="spotVT" ><label>kWh za rok VT</label>
<div id="nt" style='display:none'><input type="text" name="spotNT" ><label>kWh za rok NT</label></div>
</form>
<input id="sub" type="button" value="Ok" style="margin-left:15px;" onclick="submitForms()"/>
But this is not working. Can you help me please? Thank you
Once you are submitting one form your page reloads or terminates the javascript after that submission of form so better use Ajax for submitting multiple forms at the same time
with jquery
$("#sub").click(function(){
$("form").each(function(){
var fd = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "solve.php",
data: fd,
processData: false,
contentType: false,
success: function(data,status) {
//this will execute when form is submited without errors
},
error: function(data, status) {
//this will execute when get any error
},
});
});
});
Above code will submit every form when you click a button with id sub
It will be easier to only submit one form. You can give your select and input tag the same form name by assigning form="your-form-id".
Here's an simple example of a native Javascript implementation.
<!DOCTYPE html>
<html>
<head>
<title>Multiform - JAVASCRIPT</title>
</head>
<body>
<fieldset>
<legend>Form 1</legend>
<form name="f1" id="f1" onsubmit="return validate(this)">
<input type="text" name="username" placeholder="Username" />
</form>
</fieldset>
<fieldset>
<legend>Form 2</legend>
<form name="f2" id="f2" onsubmit="return validate(this)">
<input type="text" name="email" placeholder="Email" />
</form>
</fieldset>
<fieldset>
<legend>Form 3</legend>
<form name="f3" id="f3" onsubmit="return validate(this)">
<input type="text" name="password" placeholder="Password" />
</form>
</fieldset>
<button onclick="submitAll();">SUBMIT ALL</button>
<script>
'use strict';
function validate(form){
//forms processsing goes here...
console.log(form, form.name)
return false;
}
function submitAll(){
for(var i=0, n=document.forms.length; i<n; i++){
document.forms[i].onsubmit();
}
}
</script>
</body>
</html>
You could try this. If submitting all forms is fine for your page
$('form').submit();
Function that's in actual use:
function trySubmitAllForms() {
if ($('.saveSpinner').is(':visible')) {
return;
}
if ($('form').valid()) {
$('.saveSpinner').show();
$('form').submit();
} else {
showValidationErrorMessages();
}
}
Bismillah, try our method below, insyaAllah we hope can provide a solution for you.
document.getElementById("submit").addEventListener("click", function () {
$(function () {
$("#formid01").delay(300).submit();
$("#formid02").delay(300).submit();
});
});

Force form field value on page load & submit

How could I force a specific value within a form field on page load; and have that value 'Submit' with JavaScript or jQuery?
I tried the below; but no cigar.
<script>
window.onload = function(){
document.forms['coolform'].submit()
}
</script>
Mark-Up.
<form id="search" name="coolform" class="navbar-form form-search" action="#">
<div class="input-append">
<input id="query" type="text" class="search-query" value="Bars" >
<button type="submit" class="btn"><i class="icon-search"></i></button>
</div>
Try the following (jQuery):
$(function(){
var s = $('#search');
$('#query', s).val('The value you want to force in.');
s.submit();
});
HTML:
<input id="query" name="query" type="text" class="search-query" value="Bars" >
you could use ajax to submit the value on document.ready...
$(document).ready(function(){
var query = $('#query').value;
$.ajax({
url:'url/to/your.php',
data:'query='+query,
success:function(data){
//handle response
}
});
});
You need a name attribute on the form field, otherwise it won't be included when the form is submitted:
<input id="query" name="query" type="text" class="search-query" value="Bars" >

Categories