jQuery submit form via submit button - php

Is it possible to submit a form by clicking a div-element as if it was submitted by the submit button?
So that this PHP works:
if(isset($_POST["share"])) { /* do something*/ }
Form:
<form id="form" action="publish.php" method="POST">
<textarea name="description" maxlength="500">Description...</textarea>
<input type="submit" name="share" value="Share" />
</form>
This does NOT post the share value, $_POST['share'].
if($(".post-form").length){
$(".post-form").click(function(event) {
$("#form").submit();
return false;
});
}

Yes this is possible by using the .submit() function. You can use it like so:
// Wait until the document has been fully loaded
$(document).ready(function() {
// Bind a click event to your element
$('div').click(function(event) {
// Submit the form
// The callback should add a hidden field with the name "share"
$('form').submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', "share")
.attr('value', "Share")
.appendTo('form');
return true;
});
});
});
You can find more information here
Demo: jsfiddle

Set an id for submit button:
<input type="submit" name="share" value="Share" id="btn_submit" />
then you can control it in jquery like this:
$("#btn_submit").onclick(function(){
if(condition==true)
{
return true;
}
else
{
return false;
}
});

Related

Dynamically Added Input fields passed Validation and submit cannot to another page

I 'm beginner, In dynamically added Input fields Reference From: Validate Dynamically Added Input fields, when passed Validation and submit cannot to another page
Follow script sample.
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
when passed validation click submit butt cannot to action="/action_page_post.php"
And HTML code
<form class="commentForm" method="get" action="/action_page_post.ph">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Changes I made
changed on('submit') to submitbutton.onclick
added $('.commentForm').submit(); inside the if condition which execute if the validation is true
Reason : Since you are using event.preventDefault(), it will prevent the default behaviour of the form and so did not go to next page. So You have to submit the form manually using $(form).submit();
The below code will work on normal page but not on SO Snippet
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('input.submit').click(function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
});
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
$('.commentForm').submit();
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form class="commentForm" method="get" action="action_page_post.php">
<div>
<p id="inputs">
<input type="text" class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>

Redirect GET form with action in another url

I have a form with the action set to "/resutls". But i have a txt input and i want to check if that is not empty to redirect to another location than "/results". Is this possible?
Code example as below:
<form id="results" action="/results" method="get">
<select id="country" name="country">
....
</select>
<input type="text" name="id">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Any ideas? Can this be done with jquery?
Sure you can do that in the submit handler. Warning: I wouldn't give a form control a name of id. It does cause confusion: if this refers to the form, should this.id refer to the id of the form or the text field with name="id"?
if( !!this.somefield.value ) { //did not want to write this.id.value !!!!
this.action = '/other-url';
} else {
this.action = '/results';
}
$(function() {
$('#results').on('submit', function(e) {
e.preventDefault(); // just so we can see that form action changes
if( !!this.somefield.value ) {
this.action = '/other-url';
} else {
this.action = '/results';
}
alert( this.action );
//$(this)[0].submit(); //now submit the form
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="results" action="/results" method="get">
<select id="country" name="country">
</select>
<input type="text" name="somefield">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Yes it is possible. Just set the form element's action property using jQuery .prop().
As a simple example:
var valid = false;
// go though validation here
if (false === valid) {
$('#results').prop('action', '/some/url/to/redirect/to');
}
HTML5 provides the "required" attribute wich will prevent the form for being posted, use it like this
<input type="text" name="id" required="required">
or, if you prefer to redirect to other page instead, you can do this
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$("#results").submit(function (e){
e.preventDefault();
if($("#results input[name='id']").length < 1){
window.location.href = "your detiny url";
}
else{
this.submit();
}
});
</script>

Form not submitting through outside button using Jquery

I have a form
<div id='formdiv'>
<form action='purchase.php' method="POST" id="purchaseform">
......
<input type="submit" value="Add Purchase" />
</form></div>
After user submits the form..he is first made to confirm the enteries:
$('#purchaseform').submit(function(){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
});
where the confirm div is:
<div id='confirmdiv'>
data to be confirmed....
<input type="button" value="Confirm" id = "confirmform"/>
<input type="button" value="Cancel" id = "cancelform"/>
</div>
I am trying to submit the form once user clicks on confirm button
$('#confirmform').click(function(){
$('#purchaseform').submit();
$('#formdiv').show();
$('#confirmdiv').hide();
});
But the form is not submitting...anyone knows what am i doing wrong here??
its because when you call the $('#purchaseform').submit(); it will again read your first statement which is
$('#purchaseform').submit(function(){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
});
try using a hidden input to indicate if the datas are confirmed or not. In your form put a hidden textfield
<div id='formdiv'>
<form action='purchase.php' method="POST" id="purchaseform">
<input type="submit" value="Add Purchase" />
<input type="hidden" name="isconfirm" id="isconfirm" value="0" />
</form></div>
then in your other statement put a condition before you call return false and the other functions
$('#purchaseform').submit(function(){
var confirm = $("#isconfirm").val();
if(confirm == 0) {
$('#formdiv').hide();
$('#confirmdiv').show();
return false; }
});
then change this as well
$('#confirmform').click(function(){
$("#isconfirm").val(1); //change the value to 1
$('#purchaseform').submit();
$('#formdiv').show();
$('#confirmdiv').hide();
});
It's pretty logical that it's not submitting. After all, whenever it tries to submit, it will instead go to your submit event handler, which always returns false. You have to make sure that if the submit comes from your script instead of from the button in the form, it does submit. One way to do that is like this:
var confirmed = false;
$('#purchaseform').submit(function(){
if (!confirmed)
{
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
}
else
{
confirmed = false;
return true;
}
});
$('#confirmform').click(function(){
confirmed = true;
$('#purchaseform').submit();
$('#formdiv').show();
$('#confirmdiv').hide();
});
This can easily be edited to suit your needs. Another way to do this would be to instead bind the original event to the submit button instead of the actual submit event, but if you do that, you might get into trouble later on if you have a text field in the form and the user presses enter while it's selected. This would then directly submit without confirmation, whereas in the above solution it will neatly ask for a confirmation.
you want to have a confirm dialog, first i think that is better to use the jquery ui dialog plugin http://jqueryui.com/dialog/#modal-confirmation
Here is the code to use :
1- add "display:none" to your confirm dialog
<div id='confirmdiv' style="display:none">
data to be confirmed....
</div>
delete confirm event
$('#confirmform').click ....
2- init your dialog
$( "#confirmdiv" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Confirm": function() {
$('#purchaseform').submit();
},
"Cancel": function() {
$( this ).dialog( "close" );
}
}
});
3- Test your code
4- thats all folks
You are overriding what happens when the form gets submitted in
$('#purchaseform').submit(function(){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
});
Instead, how about you use
$('#purchaseform').find(":submit").click(function(e){
$('#formdiv').hide();
$('#confirmdiv').show();
return false;
}
Or, of course, you can set an ID on the submit button and use that.
That's because your $('#confirmform').submit() function invoke the 1st submit function again.

Ajax with multiple submit buttons

How can I change the code below so instead of a text input type with a submit button I want multiple submit buttons each with their own unique value? Everything I try just ends up with submit's value being undefined. Any help would be great!
Code source: Submit Search query & get Search result without refresh
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
You can add multiple submit buttons and attach to all of them onclick event listener. When button was clicked - get the value and send with a POST request.
<script>
$(function(){
$('input[type=submit]').click(function(){
$.post('db_query.php', {value:$(this).val()}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="">
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
</form>
If you want to use multiple submit buttons, you can catch the click event and determine which button was clicked. then run different Ajax submit. this also works when enter is hit.
//submit buttons
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str" />
<input type="submit" value="v1"/>
<input type="submit" value="v2"/>
//...more submit buttons
</form>
//submit func
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val){
case 'v1':...;
case 'v2':...
}
});
});
Here is my version - which now looks very much like Bingjies because it was written while I was testing out his version
DEMO
<form id="lets_search" action="" >
Search:<input type="text" name="q" id="q">
<input type="submit" value="Google" name="send" id="google">
<input type="submit" value="Bing" name="send" id="bing">
</form>
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val()) {
case "Bing" :
$("#lets_search").attr("action","http://www.bing.com/search");
break;
case "Google":
$("#lets_search").attr("action","https://www.google.com/search");
break;
}
});
});
Here, I would prefer to Vamsi's solution n Why not Sanjeev mk?
Give some extra thought on prefering the solution.
case: If there are mulitple submit buttons
If the user is in the text field and hits enter, the system will assume the first submit button was hit.
So, here, it would be good to go for not having mulitple submit
buttons for end user point of view
You can have multiple submit buttons in the form, no problem. They may have the same name, type etc, but just assign them different values. Like Submit Button 1 can have value="hi" and Button 2 can have value="bye".
Then when the action function is called for the button, all you have to do when entering the function is do a check with: $(this).val
HTML:
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
jQuery:
$(function() {
$("#lets_search").bind('submit',function() {
var value = $(this).val();
if(value == "hi")
do_something;
else
do_something_else;
});
});

Prevent Default for Ajax created form

I am getting the form on click from a file called test.php which contains the following:
<form method="post" class="adminTM">
<input type="hidden" name="execID" value="<?=$_POST['exec']?>" />
<input type="hidden" name="fromTM" value="<?=$_POST['TM']?>" />
<input type="text" name="toTM" value="<?=$_POST['TM']?>" />
<input type="hidden" name="symbol" value="<?=$_POST['symbol']?>" />
<button class="submitTM">SUBMIT</button>
</form>
The javascript looks like so:
$(function(){
$('.adminTMClick').live('click', function(e){
$(this).data('TM', this.innerHTML);
$.post('test.php', $(this).data(), function(data){
$(data).dialog({
modal: true,
beforeClose: function(){
$(this).remove();
}
});
console.log($('.adminTM'));
console.log($('.submitTM'));
});
});
$('.submitTM').live('click', function(e){
//originally had .adminTM with submit which failed
e.preventdefault();
alert('i am here');
return false;
});
});
How do i make it so that the form DOES NOT do the default submit action when the submit button is clicked?
Here is a fiddle that demonstrates basically what I am doing (i had to change it a bit because of the way jsfiddle works): http://jsfiddle.net/maniator/tQVnV/show/
You should use the submit() event on the form instead of the click() on the submit, since pressing enter will still submit the form (bypassing the submit button).
This should properly prevent the form from doing the default submit:
$('.adminTM').live('submit', function(e) {
// execute custom code
console.log("submit event fired");
// prevent default submit
return false;
});
jsFiddle: http://jsfiddle.net/bjorn/tQVnV/11/

Categories