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
I've been building a mail form that is supposed to pass the information into a php document that handles sanitization and mailing, but I didn't want it to refresh so i decided to use JQuery and AJAX. I'm fairly new to JQuery and haven't used any AJAX before so I am a bit of a rookie when it comes to this...
Even though I have the .submit(function(e){e.preventDefault();}); it still submits the ordinary way and gives an error when it can't find film_mail in the PHP. Which means that it isn't stopping the submit and isn't passing the code to the PHP.
I've tested with alerts and the JQuery works in to the if() but after that some thing goes wrong.
Here is the code that causes the issue (some of the classes and ids are in swedish but that shouldn't cause an error...)
HTML
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="nr" min="1">
<input id="film_antal" type="number" name="antal" min="1">
<input id="film_namn" type="text" name="namn" placeholder="Namn">
<input id="film_adress" type="text" name="adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="postnr" placeholder="Postnummer">
<textarea id="film_medelande" name="medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>
JQuery
$(document).ready(() => {
var emne = $('#emneid').val();
if (emne == 'film') {
$('#film_form').submit(function(e) {
e.preventDefault();
var mail = $('#film_mail').val();
var nr = $('#film_nr').val();
var antal = $('#film_antal').val();
var namn = $('#film_namn').val();
var adress = $('#film_adress').val();
var ort = $('#film_ort').val();
var postnr = $('#film_postnr').val();
var medelande = $('#film_medelande').val();
var submit = $('#film_submit').val();
$.post('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});
// I heard that .load() had been removed in 3.0 so i tried to use $.post() because I thougt that might work but it sadly didn't...
// but I kept the .load() incase it'd be useful
/*$('#film_form').load('formular-send.php', {
film_mail: mail,
film_nr: nr,
film_antal: antal,
film_namn: namn,
film_adress: adress,
film_ort: ort,
film_postnr: postnr,
film_medelande: medelande,
film_submit: submit,
emne: emne
});*/
});
} else {
}
})
PHP
<?php
$filmmail = $_POST['film_mail'];
?>
If there is anything else that is needed i'd be happy to post it to.
I think $('#emneid').val() returns something different than 'film' and your listener is never attached.
Can you please double check the returned value of $('#emneid').val();
In addition of other comments, I think you need to add the correct name for you button or your PHP form will not work.
<?php
$filmmail = $_POST['film_mail']; //for the moment your need to put $_POST['mail'] because your button is named mail instead of film_mail
?>
Please also take care in production / later use, don't use directly $_POST or your code will be vulnerable from some SQL injection and so on. Take a look at htmlspecialchars function.
Edit :
I think you can just use HTML form and php to post your data, without posting it via JS/Jquery. If you want to have some data validation before sending it, you can just call an event before submit like described in this post : (Validate form before submit jquery)
I think you maybe have a problem with your selector to trigger the function, I don't know the submit function but maybe try with on('submit') or at least it will work with on('click').
$(document).on('click', '#film_submit button[type=submit]', function(e) {
var isValid = $(e.target).parents('form').isValid();
if(!isValid) {
e.preventDefault(); //prevent the default action
}
});
<button> does not have attribute type, but <input> has, try change <button> to <input>
UPD
Where is the tag with id of #emneid?
Try this. Please replace your HTML with my HTML code.
<div id="film" class="hidden" >
<form id="film_form" action="formular-send.php" method="post">
<input id="film_mail" type="text" name="film_mail" placeholder="Mail adress">
<input id="film_nr" type="number" name="film_nr" min="1">
<input id="film_antal" type="number" name="film_antal" min="1">
<input id="film_namn" type="text" name="film_namn" placeholder="Namn">
<input id="film_adress" type="text" name="film_adress" placeholder="Adress">
<input id="film_ort" type="text" name="ort" placeholder="Ort">
<input id="film_postnr" type="text" name="film_ort" placeholder="Postnummer">
<textarea id="film_medelande" name="film_medelande" placeholder="Medelande"></textarea>
<button id="film_submit" type="submit" name="submit">Skicka</button>
<div class="error-mesage" ></div>
</form>
</div>
For a project, I need to generate a dynamic html form that will send POST info to a PHP page via the ACTION field.
The form has not to be static, it has to be dynamic so the user has to be able to generate(ADD) a not fixed(dynamic) number of input tags, then when all the inputs are generated and filled the user may click on submit button and send all the info to a php document via post.
I'm completely lost
I've been playing with this piece of code that generates the inputs but I'm not able to send the data via post to the php file
<script>
var choices=[];
choices[0]="one";
choices[1]="two";
function addInput(divName){
var newDiv=document.createElement('div');
newDiv.innerHTML="<input type='text'>";
newDiv.innerHTML=newDiv.innerHTML+"</input>";
document.getElementById(divName).appendChild(newDiv);
}
</script>
<form class="new" method="post" action="action.php">
<div id="dynamicInput">
</div>
<input type="button" value="Add" onclick="addInput('dynamicInput');" />
<input type="button" value="Save" />
</form>
To submit the form, one possible scenario is to change the type of Save button to submit:
<input type="submit" value="Save" />
Also add name property to your auto generated inputs. Otherwise you won't access the submitted $_POST data:
<input name="enter_name[]" type='text'>
As you see, I'm concatenating [] to the input field. That will convert all submitted data into an array. Otherwise, that last one auto generated input will overwrite the previous entered data.
just change your input type to submit instead of save
<input type="submit" value="Save" />
and you don't need to create new div each time to create an input you can either append it to the div you already have
document.getElementById(divName).innerHTML+= "<input type='text' name= 'added_input[]'/>";
or
var newInput=document.createElement('input');
// if you want each input in separate lines
newInput.style.display = "block";
newInput.setAttribute("name","added_input[]");
document.getElementById(divName).appendChild(newInput);
and in your php file you can get post values like this :
for ($i = 0; $i < $_POST['added_input']; $i++){
echo $_POST['added_input'][$i];
}
for more option to get post values see This Question
I have a tip section that can be "custom" input from a customer. When the customer enters a value, I want to pass it to PHP for updating the order.
I'm unsuccessful and I'm thinking I'm approaching this problem the wrong way since I can't get it to work. What options are available to me without using AJAX?
The tip section:
<?= ($receipt['tip'] > 0 ?
'<tr id="tip-area"><th>Tip</th>
<td><textarea id="tip" name="update_tip" readonly>'. $receipt['tip'].'</textarea></td>
</tr>'
: '') ?>
My form which has different tip options:
<form method="post">
<tr>
<button title="20% Tip" type="submit" name="update_tip" id="update_tip" class="tip-button"
value="<?= ($_SESSION['order']['quote']['subtotal'] * 0.2); ?>">
<small>20%<br><?= number_format(($_SESSION['order']['quote']['subtotal'] * 0.2), 2) ?></small>
</button>
<button title="Edit Tip" type="button" name="update_tip" id="custom-tip" class="tip-button">
<small>Edit<br>Tip<br></small>
</button>
<button title="Save Tip" type="submit" id="save_tip" class="hidden">
<small>Save<br>Tip</small>
</button>
</tr>
</form>
My jQuery:
$('#custom-tip').click(function(){
$('#tip').removeAttr('readonly').focus();
$('.tip-button').addClass("hidden");
$('#save_tip').removeClass("hidden");
});
$('#save_tip').click(function (){
var tip = $('textarea#tip').val();
$('<input type="hidden" name="update_tip" value="' + tip + '">').submit();
});
$('#tip').focus(function(){
this.value = '';
});
When they press "Edit Tip", the readonly property is remove, the area comes into focus and value is cleared.
Then the user should enter a value and hit Save.
Then I'm trying to retrieve the value they entered.
I think this is what you want:
$("form").submit(function() {
$("<input>", {
type: "hidden",
name: "update_tip",
value: $("#tip").val()
}).appendTo($(this));
});
This will create the hidden input with the value from the textarea and append it to the current form when before the form is submitted.
You need to have PHP code on the same page (because your form does not specify an action) that handles the data. Use the 'name' attribute for your input to specify the key of the value you wish to access in the $_POST super global. For example, if I post a form with the following code:
<form method='POST'>
<input type='hidden' value='hello' name='world'>
<input type='submit' value='submit'>
</form>
Then in PHP, I can access the value of the element with the name "world" with the following code:
$_POST['world']
Use this syntax to acquire the data from the form and persist it/update it.
As the title says This is the code that I tried with. The forms must appear one by one because information from previous forms determine how the next ones will look.
$(document).ready(function(){
$('#first_form').submit(function(){
$('#first_form').fadeOut('fast');
$('#second_form').fadeIn('fast');
});
});
<form action="new_patch.php" method="POST" id="first_form">
Title: <input type="text" name="patch" placeholder="Patch 4.20">
<br/>
Number of Champions: <input type="number" name="champ_number" min="1" max="99">
<br/>
<input type="submit" value="submit">
</form>
<form action="new_patch.php" method="POST" id="second_form" style="display: none;" >
<input type="text" value="text">
<input type="submit" value="submit">
<?php
$champ_number = null;
if(isset($_POST['champ_number']))
{
$champ_number = $_POST['champ_number'];
for($champ_number;$champ_number>0;$champ_number--)
{
echo "<br/>Champion ".$champ_number."<input type=\"number\" name=".$champ_number." min=\"1\" max=\"99\">";
}
}
?>
</form>
You're mixing client-side and server-side form code. Submitting the form will reload the page entirely, so from the looks of your code it will fade in the new form when the old form is submitted, but then reload the page so the old form will show again anyway.
You could either:
Let the PHP determine how the next form appears based on the submission of the first form, e.g. if (isset($_POST["First_form_submit"]) { Show second form... }
Probably better and more user-friendly: make the second form appear below once the user has filled in the relevant inputs on the first form before they've submitted
you can use:
$('#first_form').submit(function(){
$('#first_form').fadeOut(function() {
$('#second_form').fadeIn('fast');
});
return false;
});
From the jQuery documentation the syntax is fadeIn( [duration ] [, complete ] ) it accepts a duration and a onComplete callback that you can use to execute the next action when the first is completed.
I did this once too, just add a submit class to the button and make it like this:
<input type="submit" value="submit" class="submit">
Change script to a click function.
$(document).ready(function(event){
event.preventDefault();
$('.submit').click(function(){
$('#first_form').fadeOut(400);
$('#second_form').fadeIn(400);
});
});
PS, also you need to prevent submit default...otherwise it will just submit the form, see this JSfiddle