Send form with both triggers for action and onclick - javascript

I need to connect one button to 2 activities, in this case the form argument "action" and button argument "onclick" inside a form.
The forms "action" is PHP-based class and the button's "onclick" is connected to a javascript.
Environment:
The question is generic but to clarify I will use the form in later stage in a Laravel 8 environment. This means that the handling of form "action" is being taken care of by Laravel through a route. The onclick should be triggered and the javascript is physically positioned at the end of the Laravel blade view.
The problem:
I noticed that having the button inside the form, runs the form "action", but prevents the button argument "onclick" to trigger the javascript. If put the mentioned button outside of form, then one can trigger the form, and the button outside the form but ends up with need of 2 buttons which break simplifying the user flow.
Question:
How can I trigger both form "action" and the javascript function from one button? Note! It is not needed that javascript is being trigger by "onclick" if there are other ways to trigger the javascript.
Test-1: Basic form
<form
method="post"
action="/payment-checkout"
>
<button type="button" name="button" onclick="initCheckout()">Send</button>
</form>
Result test-1:
forms action is being executed, but not javascript.
Test-2: Attempt to solve problem using form attribute "onsubmit":
<form
id="myForm"
method="post"
action="/payment-checkout"
onsubmit="submitFormFromJavascriptFunction()"
>
<input type="submit" name="" value="Submit">
</form>
function submitFormFromJavascriptFunction() {
// Execute this...
}
document.getElementById("myForm").onsubmit = function() {submitFormFromJavascriptFunction()};
Result test-2:
forms action is being executed, but not javascript.

Try to trigger sumbit event on a button click manually by using
document.getElementById("myForm").submit();
from your onclick function
Example
function submitform() {
console.log('Inside the onclick function');
document.getElementById("myForm").submit();
}
<form action="/action_page.php" id="myForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<button type="button" onclick="submitform()">Submit</button>
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>

Below is an example of doing a conventional html form submit with javascript execution on submit of the form.
The form gets submitted based on the return value of the javascript function.
Javascript function is attached to onsubmit event of the form.
button is a normal submit button with no event handler attached to itself.
//this function getts called on submission of the form via submit button.
//Its return value dictates whether form will be submitted or not
function checkQuery(){
var query = document.getElementById('myQuery');
if(query.value==""){
alert("Please enter your search query")
return false; //form will not submit
}
return true;//form will get submitted and laravel will see that submit button was pressed
}
<form
method="get"
action="https://stackoverflow.com/search" onsubmit="return checkQuery();"
>
<input type="text" id="myQuery" name="q" placeholder="your search query here">
<button type="submit" name="button">Search Now</button>
</form>
Your Test 2 should be like this:
<form
id="myForm"
method="post"
action="/payment-checkout"
onsubmit="return submitFormFromJavascriptFunction()"
>
<input type="submit" name="" value="Submit">
</form>
function submitFormFromJavascriptFunction() {
console.log("submitFormFromJavascriptFunction is getting called");
return true // or false based on your logic
}
// no need for below line
//document.getElementById("myForm").onsubmit = function() //{submitFormFromJavascriptFunction()};

Related

Enter Key not working in button

i'm using button key for my project but this is not work when i push Enter Key.
why 'enter key' not working in this form?
<form action="" method="post">
<input type="text" >
<input type="button" >
</form>
how this is work with javascript, plz help me
i will not sue type="submit"
It seems you want implicit submission:
A form element's default button is the first submit
button in tree order whose form owner is that
form element.
If the user agent supports letting the user submit a form implicitly
(for example, on some platforms hitting the "enter" key while a text
field is focused implicitly submits the form), then doing so for a
form whose default button has a defined activation behavior
must cause the user agent to run synthetic click activation steps
on that default button.
Therefore, the button must be a submit button, not a button in button state:
<input type="submit">
I think an <input type="submit"> is what you want :)
$(form).on('submit', function{
//do whatever you want...
})
<form action="raftel">
<input name="name" type="text"/>
<input name="password" type="password"/>
<input type="submit"/>
</form>

i want to check form validation by input type button, not by submit, could any one help in this?

i want to only validate the form and don't want to submit it, so that i can use the form values in modifying other part of the same html page by calling a function "myfunction()" after form validation. for this i want to use a button suggest me required code.my code is following :-
<form name="form1">
<input type="text" name="name1" required></input>
<button onclick="myfunction()" ></button> // i want to validation of form by this button
</form>
You can try this by setting onsubmit event of form to return false; as follows:
<form name="form1" onsubmit="return false;">
<input type="text" name="name1" required></input>
<button onclick="myfunction();" ></button>
</form>
This will not submit the form on clicking the button but will execute myfunction() instead.
If you know jQuery, then you can do this as follows:
$('form[name="form1"]').submit(function (event) {
// This will prevent form being submitted.
event.preventDefault();
// Call your function.
myfunction();
});
For maintainability consider adding an event listener to the button by selection instead of inline. When the button is clicked an event object is passed to the callback. Event objects have a number of properties and methods. In this case you're looking for the method "preventDefault" which prevents the default action of the event which in this case is a form submit. An example:
<form name="form1">
<input type="text" name="name1" required />
<button id="my-button"></button>
</form>
document.getElementById('my-button').addEventListener('click', function(e){
e.preventDefault();
var form = document.forms['form1']; //or this.parentNode
//do stuff
}, false);
i have achived this goal by modifying code as follow:-
<form name="form1" onsubmit="myfunction();return false;">
<input type="text" name="name1" required></input>
<button >check form and call function</button>
</form>
by this i am able to check form and call my function and form is also not submitted in this case.
now i want to reset the form without clicking any button. suggest javascript code for this.
HTML form validation by input type button, not by submit.
Try this
<form name="form1" onsubmit="myfunction(); return false;">
<input type="text" name="name1" required></input>
<button type="submit">Submit</button>
</form>

Submitting form using button on enter

I have an html form that I want to only submit from a button located outside my form. I am using javascript to perform some verification and do not want the form to submit unless my javascript functions succeed. I found that if I have the button inside the form it will always submit regardless of the javascript, but if I have it outside the form when a user presses enter it simply submits the form. How can I force enter to perform the button javascript instead of submitting?
<form name="form1" action=<?$_SERVER["PHP_SELF"].'?'.$_SERVER["QUERY_STRING"]?> method="post">
<input type="text" maxlength="5" size="5" name="frmZip" value="">
<input type="hidden" name="frmLat" value="200">
<input type="hidden" name="frmLng" value="200">
<input type="submit" disabled="disabled" style="display:none" />
</form>
<button type="button" id="GetCoordinates" onclick="doClick();">Find Stores</button>
EDIT:
Found my solution.
I changed from
</form>
<button type="button" id="GetCoordinates" onclick="doClick();">Find Stores</button>
to
<input type="button" name="frmSubmit" onclick="doClick();" value="Submit">
</form>
This prevented the button from submitting the form so I submitted it in my doClick() via javascript.
EDIT 2:
While this seemed to work for a time, it has stopped catching the enter keystroke. I updated my button to:
<input type="submit" name="frmSubmit" onclick="return doClick();" value="Find Stores">
And always returned false in doClick(). This allowed me to submit the form via javascript once everything had executed.
While this doesn't answer your direct question, you can actually keep the button and simply use your validation on the form submit:
<form onsubmit="return validateForm()">
Then, in your validateForm method, return true or false indicating whether or not the validation has passed.
However to answer your direct question, you can also use the same approach on the submit button which will prevent the form from being submitted.
Update
As pointed out in the comments, an unontrusive solution is often desirable so here's that:
document.getElementById('theForm').onsubmit = function() { return validateForm(); };
Your button inside the form will not submit the form on enter if you add preventDefault...
$("form").submit(function(e) {e.preventDefault();});

How to prevent from refreshing after submitting?

I got this code right here which executes the function validate() when submit is clicked. The function changes some of the text in the page. But I can't see the effect because the page automatically refreshes after submission:
<form name="myForm" onsubmit="validate(); return false;">
Age: <input type="text" name="age" />
Height (meters): <input type="text" name="height" />
Weight (kilograms): <input type="text" name="weight" />
<input type="submit" value="Submit">
</form>
How do I prevent the page from reloading after each submission?
You can use a test button inside your form
<input type="button" value="Test button" onclick="validate();">
Once solved, remove the button.
You can also use Firebug (or equivalent) to add a breakpoint in your javascript code.
The submit event fired by your form automatically initiates the form action. If no form action is declared, it refreshes the page. Your need to prevent this default action from occuring before validation, then submit the data after it has passed validation.
Add preventDefault() to your validation code.
Make sure you add return false; in your validate() function.
That will prevent the form to be submitted.
Example :
function validate() {
//Validation code goes here
return false;
}

Submit form to another page (which is different from the page used in ACTION)

I have a form like this:
index.php
<form method="post" action="send.php">
<textarea name="msg" id="msg"></textarea>
<input type="submit" value="Send" />
</form>
So, if I enter something in textarea and clicked on "Send", it is submitted to "send.php" page. But I want to include another button for previewing it. That is, when this button is clicked, the above form is submitted to "preview.php" which will be opened in a new blank window/tab (original page ie. index.php will be there intact). This is to display a preview of the message, that the user is going to send.
I do not know how to do this.
Use Javascript to temporarily change the action and target:
<form method="post" action="send.php" id="idOfForm">
<textarea name="msg" id="msg"></textarea>
<input type="submit" value="Send" />
</form>
<button onclick="doPreview();">Preview</button>
<script type="text/javascript">
function doPreview()
{
form=document.getElementById('idOfForm');
form.target='_blank';
form.action='preview.php';
form.submit();
form.action='send.php';
form.target='';
}
</script>
There is now an attribute for the submit input that handles this:
<input type="submit" formaction=”differentThanNormalAction.php”>
Give your form an ID (form1). The action of the current form can be controlled like this:
function setPreview() {
$('#form1').attr('target','_blank')
$('#form1').attr('action','http://yourpreviewurl.php')
$('#form1').submit()
}
function setSubmit() {
$('#form1').attr('target','')
$('#form1').attr('action','http://yourposturl.php')
$('#form1').submit()
}
Have two buttons, both type="button", one to call setPreview and another to call setSubmit
You can use JavaScript to change the action of the form when the button is clicked and then submit it.
Or simply submit the form via AJAX and then redirect after you get a response.
<form onreturn="someJavascriptFunction()" action="" method="">
creating a js function able to open this preview page

Categories

Resources