Insert Back Button in Form - php

I feel like this is simple but i'm not sure where to start.
I have a multi-page form that the user clicks 'next' through to get onto the next page. I would like to also give them a 'back' button so that they can go back and change their response if they need to. How do I insert a 'back' button that still keeps their data on previous pages?
I don't need to track what their response was before or anything like that, just the final response is all that's necessary.
My form has a lot of code, so if you need to see another example please let me know:
Code at the very start of form:
<form action="surveysubmit.php" method="post" enctype="multipart/form-data">
Code to proceed to 'next' page and where I need the 'back' button:
<input class="submit-next" type="submit" name="submit_second" id="submit_second" value="" />
Code to submit final page (and entire form):
<input class="submit-end" type="submit" name="submit_ninth" id="submit_ninth" value="" />

If on clicking the "next" button the user is redirected to a new page each time then you can use localStorage to store the values which the user entered in the previous page,
For this edit the submit button in your each page as follows,
<input class="submit-next" onclick="saveValues()" name="submit_second" id="submit_second" value="" />
Your JavaScript code,
function saveValues(){
//fetch all the form values
var name = document.getElementById("inputName").value;
//Store it in the localStorage
localStorage.setItem("name", name);
//Now submit the form
document.getElementById("myForm").submit();
}
Now on every page you have to check whether their are any set localStorage values,
window.document.onload = function(e){
var name = localStorage.getItem("name");
document.geteElementById("inputName").value = name;
}
To display back button,
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>

Related

Why is my jquery call refreshing the page? [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

HTML TwoButtons that saves and move to the next page and the second saves and clear the form in order to add new data

i want to have two buttons in my page that the one saves the data and move to the next page of the site and the other button saves the data and then clear all the fields to enter new data. I did the one button that saves the data and move to the next page but for the second button does not clear the fields but also moves to the next page. How can I fix that?
if(isset($_POST['submitted']))
{
.
.
.
header('Location: education.php');
}
My button code is this...
<input type="submit" value="Next" name="submit" />
<input type="submit" value="Add New & Save" />
Try this code :
if(isset($_POST['submitted']))
{
if($_POST['submitted']=="Next")
{
//perform inserting data and redirect
header('Location: education.php');
}
else if($_POST['submitted']=="Add New & Save")
{
//Clear all fields of form and save the data.
}
}
And give your submit button same name:
<input type="submit" value="Next" name="submitted" />
<input type="submit" value="Add New & Save" name="submitted"/>
OR you can try this also :
if(isset($_POST['submit_next']))
{
//perform inserting data and redirect
header('Location: education.php');
}
else if(isset($_POST['submit_new']))
{
//Clear all fields of form and save the data.
}
And give your submit button different name:
<input type="submit" value="Next" name="submit_next" />
<input type="submit" value="Add New & Save" name="submit_new"/>
One way you could accomplish what you want is to have the ADD NEW button be a separate form. You can have more than one form on a page. So, remove the 'Add New & Save' button from this form and use the 'Next' button for one form and the 'Add New' button for a second form.
Obviously, you would have to change the header url to the current page url (i.e. header('Location:education.php') would have to be changed to point to the page your forms are on. That will save your data and refresh the page, by invoking it again.
And, you would have to include a conditional statement that would determine which button had been clicked, to determine which page to navigate to.

how to get value of two normal button in a single form?

I have a form in which i have two input button one for multiple delete and another for multiple suspend items. like this-
<form>
<input type="checkbox" name="check_item[]" value="<?php echo $users['user_id']; ?>" />
<input type="button" id="suspendall" name="suspendall" value="Suspend" />
<input type="button" id="deleteall" name="deleteall" value="Delete" /></td>
</form>
when I click on delete or suspend it ask for confirm that event by jquery like-
$('#deleteall').click(function() {
if(confirm('Really Want To Delete This?')){
$('#listing').submit();
}
});
if it confirm cancel form is not submitted and if it confirm OK form is submitted and on submission i have to delete or suspend that item from db. I have write this code for this-
if(isset($_POST['deleteall'])){
$check_array = $_POST['check_item'];
$usersId = implode($check_array,',');
$db->deleteUser($usersId);
}
if(!empty($_POST['suspend'])){
$check_array = $_POST['check_item'];
$usersId = implode($check_array,',');
$db->suspendUser($usersId);
}
the problem I am facing is both times when the form is submited i got only array of ids of check boxes. I am not able to identify which button is clicked because I am not getting button value. that why its not working, and if I changed these button into submit button its working very nice but didn't ask for confirm the event. What should I do for that. Do anyone have any solution for that, Please help me. thanks
When submitting with jQuery().submit() the button on which was clicked is lost.
You could try to not submit() the form in the click handler but instead call evt.preventDefault() when ! confirmed().
In you HTML form has a hidden form field.
On the JS event set the value of the hidden field before submitting
$('#deleteall').click(function() {
if(confirm('Really Want To Delete This?'))
{
$("#hiddenFormId").val("deleteAll");
$('#listing').submit();
}
});
Then use this type of code in your PHP (Sorry not a PHP programmer)
if $_POST['hiddenFormId'] == 'deleteAll'

How to do different javascript actions with two buttons in one form?

I'm trying to do two different javascript actions with jquery for my php form which has two submit buttons: 'save' and 'next'. The idea is that both button submits form that saves data into db, but while 'next' goes through client-side validation and progress further, the 'save' just skips validation, returns true and the user stays on the form.
<form id="form" name="form" method="post" action="?action=my_php_form">
<input type="submit" name="save" class="save" id="save" value="save"/>
<input type="submit" name="next" id="next" class="next" value="next"/>
</form>
I already managed to succeed when user clicks either 'save' or 'next' after reload, but if user clicks 'next', launches validation and submit returns false, he cant click 'save' and ignore validation anymore. What might be the cause of this?
$(function() {
//Lets skip the whole thing if save is clicked
$('#save').click(function() {
$('#form').submit(function() {
return true;
});
});
$('#next').click(function() {
$('#form').submit(function() {
var invalid = 0;
//A lot of crazy validation, if some invalid stuff then increment increment invalid
if(invalid > 0) {
return false;
}
else {
return true;
}
});
});
});
I think I would do something like this :
$(function() {
//Lets skip the whole thing if save is clicked
//Actually, no binding is needed as the button is already a submit button
//Thx to Ocanal
$('#next').click(function() {
var invalid = 0;
//Validation process
if(invalid) {
$('#form').submit();
} else {
return false;
}
});
});
Why would you skip validation, especially if it so crazy ? Anyway the problem is here
$('#form').submit(function() { ... }
this doesn't overwrite the submit event handler, this ADDS a function to it. Therefore if you first click next then save , the function you defined for next will still be triggered when clicking on save.
While it's not clear with the notation, it's quite logic : that's what allows you to "add" action to your documentReady event from wherever you wish, not only from a central place.
You can use a different type for your non-submit button.
You'll want something like this:
<form id="form" name="form" method="post" action="?action=my_php_form">
<input type="submit" name="save" class="save" id="save" value="save"/>
<input type="button" name="next" id="next" class="next" value="next"/>
</form>
I think what's happening to you now is that both buttons are acting as your "submit" button, so the form is trying to submit, regardless of which button you're clicking, or what functions you've added to the EventListener.
First of all, Java Script is created every time when refreshing the page. It's important to understand that.
Now, if you click on the button 'Save' of type submit, your information will pack up in the form packet and sent to the server. The submit action requires reloading of the page(!).
Therefore, if you want to keep values ​​in fields (if that's what you want) you may use PHP.
Using PHP is not complicated. I combine the code inside the <body> tag and before the <form> tag.
The code checks whether there is a value in the 'Save' field of $_POST variable, if true, we will save the received values.
And then, I present the values ​​using variable access <? = $name ?>. That's it.
<?php
$name = "";
$credit = "";
if(isset($_POST['save'])) {
$name = $_POST['name'];
$credit = $_POST['creditCard'];
}
?>
<form id="form" name="form" method="post" action="good.php">
<input type="text" name="name" value="<?=$name ?>" />
<input type="text" name="creditCard" value="<?=$credit ?>"/>
<input type="submit" name="save" class="save" id="save" value="save"/>
<input type="submit" name="next" id="next" class="next" value="next"/>
</form>

check if html button is checked in php

I have a button on my form. I want to check if it's pushed or not. I tried like this:
<input type="button" name="btn" id="btn" class="btn1" value="Creaza Sondaj" />
if (isset($_POST['btn']))
But this method is only working for submit buttons. How can I check if a button is pushed?
If you want to handle pushing button with PHP, change it's type to submit.
Otherwise handle click event with JavaScript.
What you might want to do is when a button is pressed, add a hidden input field to your form with javascript. That hidden field won't be displayed to the user, but once the form is submitted, your PHP will be able to read the value of that input. If the value exists, the button was pressed.
Here is a jQuery example -
$('#btn').on('click',function(){
$('#form').append('<input type="hidden" name="form_data[btn]" value="btn_clicked!" />');
});
Here is a "raw" JavaScript example, execute this code with an onclick event -
var newInput = document.createElement('input');
newInput.innerHTML = '<input type="hidden" name="form_data[btn]" value="btn_clicked!" />';
document.getElementById('form_id').appendChild(newInput);
Make sure to give it a name attribute so that you'll know where to look for the values in your PHP.
You have to use $_POST i.e. make your form submit to the page with:
<?php
if (isset($_POST['btn']))
Otherwise, you can use JavaScript/jQuery like:
<input type="button" name="btn" id="btn" class="btn1" value="Creaza Sondaj" />
<script>
$('#btn').click(function(){
// do something
});
</script>

Categories