I have the following script, it's just an example of my actual code, but it's behave the same as the actual one:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="http://google.com/">
<input type="text" name="item_name" />
<input type="hidden" name="submit" value="save" />
Submit
</form>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
jQuery(function($){
$('#save').on('click', function(e){
e.preventDefault();
$('form').submit();
});
});
</script>
</body>
</html>
You can see, there is a tag with id save, which is when this link is clicked, the form should submit, but it doesnt. this is caused by a hidden input with its name submit, if I change the name it just works well.
tried this on both chrome and firefox on linux. anyone can explain this?
here is the fiddle
-- EDIT --
I tried using native click event:
document.getElementById('save').onclick = function(e){
e.preventDefault();
document.getElementsByTagName('form')[0].submit();
}
form cannot be submited too.
I think this is the same issue as this:
TypeError: e[h] is not a function
Having an input named submit adds a "submit" property to the form, meaning you can't call .submit() as a function.
You should name your hidden input something else.
Your HTML should look like this.
<form action="index.php">
<input type="text" name="item_name" />
Submit
</form>
You can fix it by using the trigger('submit')
jQuery(function($){
$('#save').on('click', function(e){
e.preventDefault();
$('form').trigger('submit');
});
JsFiddle
You need to change the name of the input button from "submit" to something else. Having an element named "submit" causes the form's submit method to no longer work, which means the form cannot be submitted via JavaScript (at least, not easily).
The reason for this is because an input element named "submit" can be referenced by its name like this: form1.submit. That is, the input element is added as a property of the form object, with the property name being the name of the input element. That basically hides the submit function that is on the form's prototype.
This is jQuery Naming ambiguity problem. you should not declare any
form element name id submit when invoke it conflict duplicate reference.
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
Depending on the browser, the Enter key may only cause a form
submission if the form has exactly one text field, or only when there
is a submit button present. The interface should not rely on a
particular behavior for this key unless the issue is forced by
observing the keypress event for presses of the Enter key.
As the .submit() method is just a shorthand for .on( "submit", handler ), detaching is possible using .off( "submit" )
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures.
Related
I'm trying to submit a form using an anchor tag. However, the validation function doesn't seem to get triggered. I've since replaced the anchor with a submit button and it now works. Still, I'm curious why the previous anchor link didn't work.
The code is
function validate() {
/* validation code here */
return status;
}
<form id="myForm" action="/response_page.php" onsubmit="return validate();" method="POST">
<!-- form elements here -->
Submit
</form>
With this code, clicking the link goes straight to *response_page.php*. But when replaced with a submit button
<input type="submit" value="submit" />
WITHOUT changing the validate function and form tag, the validate function is called correctly. What's wrong with the anchor?
Thanks
This is expected behavior.
From the MDN on the submit function :
The form's onsubmit event handler (for example, onsubmit="return
false;") will not be triggered when invoking this method from
Gecko-based applications. In general, it is not guaranteed to be
invoked by HTML user agents.
If you want to validate your code in your link, just call the validate function explicitely :
<a id=subbut href="#" class="submit_button">Submit</a>
...
document.getElementById('subbut').addEventListener('click', function(){
if (validate()) document.getElementById('myForm').submit();
});
How can I specify which submit button to submit with?
The current example just submits the first submit button, with $("form").submit(); but how can I make it so it chooses the submit button by id or name?
<html>
<script>
$("form").submit();
</script>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" />
//other inputs
<input type="submit" value="Enter" name="enter" id="enter">
<input type="submit" value="Void" name="void" id="void">
<input type="submit" value="Refund" name="refund" id="refund">
</form>
</html>
Simulate a click to that element:
$("#circle2").click();
Also, you don't need action="<?=$_SERVER['PHP_SELF']?>". Forms submit to the current page by default.
First of all, why do you want to submit the same form with 3 different buttons?
It is a bad structure. Your code also has all the 3 buttons with the "id" attribute which is included in the <input> tag twice.
Based on your question, I could figure out you would want the submit button to say different things under different conditions.
Have a single button like this :
<input type="submit" name="submit" value="Enter">
You could always change what your button says, or how it looks like with JQuery :
if(condition){
$('#submit').val('.....');
// You can also change more stuff as you want.
}
Then you would want to submit the form
$('#submit').click(function(e)){
e.preventDefault();
$('form').submit();
}
By id
You can select the element by id easily with $('#my_btn') and you can click on it using the jQuery method click().
By name (or any other attribute
Other attributes are a bit harded (but not complex)
You select the element with $('input[name=some_name]')
Examlpe using your code
Here is an example which shows how you can get elements by name and click on them, click the submit buttons to see what happens: http://jsfiddle.net/nabil_kadimi/99v93/2/
Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.
I have a form. Outside that form, I have a button. A simple button, like this:
<button>My Button</button>
Nevertheless, when I click it, it submits the form. Here's the code:
<form id="myform">
<label>Label
<input />
</label>
</form>
<button>My Button</button>
All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.
<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>
I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.
<button type="button">My Button</button>
Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):
The missing value default and invalid value default are the Submit
Button state.
return false; at the end of the onclick handler will do the job. However, it's be better to simply add type="button" to the <button> - that way it behaves properly even without any JavaScript.
By default, html buttons submit a form.
This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)
In other words, the button type is "submit" by default
<button type="submit">Button Text</button>
Therefore an easy way to get around this is to use the button type.
<button type="button">Button Text</button>
Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead
To find out more, check out the Mozilla Developer Network's information on buttons: https://developer.mozilla.org/en/docs/Web/HTML/Element/button
Dave Markle is correct. From W3School's website:
Always specify the type attribute for
the button. The default type for
Internet Explorer is "button", while
in other browsers (and in the W3C
specification) it is "submit".
In other words, the browser you're using is following W3C's specification.
Another option that worked for me was to add onsubmit="return false;" to the form tag.
<form onsubmit="return false;">
Semantically probably not as good a solution as the above methods of changing the button type, but seems to be an option if you just want a form element that won't submit.
It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)
Some reference material
For accessibility reason, I could not pull it off with multiple type=submit buttons. The only way to work natively with a form with multiple buttons but ONLY one can submit the form when hitting the Enter key is to ensure that only one of them is of type=submit while others are in other type such as type=button. By this way, you can benefit from the better user experience in dealing with a form on a browser in terms of keyboard support.
Late in the game, but you don't need ANY JavaScript code to use a button as a button. The default behavior is to submit the form, most people don't realize that. The type parameter has three options: submit (default), button and reset. The cool thing about this is if you add an event handler it will bypass submitting the form.
<button type="button">My Button</button>
There is also way to prevent doing the submit when clicking the button.
To achieve this, you have to use event.preventDefault() method.
document.querySelector("button#myButton").addEventListener("click", (event) => {
document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you submit this!<br>";
event.preventDefault();
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<form id="myform">
<label>Label
<input />
</label>
<button id="myButton">My Button</button>
</form>
<div id="output-box"></div>
<script src="src/script.js"></script>
</body>
</html>
Why is it that a <form> with a single <input> field will reload the form when the user enters a value and presses the Enter, and it does not if there are 2 or more fields in the <form>?.
I wrote a simple page to test this oddity.
If you enter a value in the second form and press Enter, you'll see it reloads the page passing the entered value as if you called GET. why? and how do I avoid it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testFormEnter</title>
</head>
<body>
<form>
<input type="text" name="partid2" id="partid2" />
<input type="text" name="partdesc" id="partdesc" />
</form>
<p>2 field form works fine</p>
<form>
<input type="text" name="partid" id="partid" />
</form>
<p>One field form reloads page when you press the Enter key why</p>
</body>
</html>
This is a little known "Quirk" that has been out for a while. I know some people have resolved it in various ways.
The easiest bypass in my opinion is to simply have a second input that isn't displayed to the user. Granted not all that user friendly on the backend, it does work to resolve the issue.
I should note that the most common place that I hear of this issue is with IE specifically and not with FireFox or others. Although it does seem to affect them as well.
This is a known bug in IE6/7/8. It doesn't appear that you will get a fix for it.
The best workaround you can do for this, is to add another hidden field (if your engineering conscience permits). IE will no longer auto-submit a form when it finds that there are two input-type fields in the form.
Update
In case you were wondering why this is the case, this gem comes straight out of the HTML 2.0 specification (Section 8.2):
When there is only one single-line text input field in a form, the
user agent should accept Enter in that field as a request to submit
the form.
No, the default behaviour is that on enter, last input in the form is submitted.
If you don't want to submit at all you could add:
<form onsubmit="return false;">
Or in your input
<input ... onkeypress="return event.keyCode != 13;">
Of course there are more beautiful solutions but these are simpler without any library or framework.
Pressing Enter works differently depending on (a) how many fields there are and (b) how many submit buttons there are. It may do nothing, it may submit the form with no 'successful' submit button, or it may pretend the first submit button was clicked (even generating an onclick for it!) and submit with that button's value.
For example, if you add an input type="submit" to your two-field form, you'll notice it too submits.
This is an ancient browser quirk going back at least as far as early Netscape (maybe further), which is unlikely to be changed now.
<form>
Invalid without an ‘action’. If you don't intend to submit anywhere, and you don't need radio button name grouping, you could just completely omit the form element.
Here is the code that I used would use to solve the problem:
<form>
<input type="text" name="partid" id="partid" />
<input type="text" name="StackOverflow1370021" value="Fix IE bug" style="{display:none}" />
</form>
It's not reloading the page as such, it's submitting the form.
However, in this example because you have no action attribute on the form it submits to itself which gives the impression of reloading the page.
Also, I can't repro the behaviour you describe. If I am in any text input in a form and I press Enter it submits the form, no matter where in the form the input is located or how many inputs there are.
You might want to try this out some more in different browsers.
as vineet already said, this is rooted in the html 2.0 specification:
here is how to prevent this from happening without screwing up your urls:
<form>
<input type="text" name="partid" id="partid" />
<input type="text" style="display: none;" />
</form>
Thanks to everyone who answered. It's an eye opener that a form with a single field acts differently then a form with many fields.
Another way to deal with this automatic submit, is to code a submit function that returns false.
In my case I had a button with an onclick event, so I moved the function call with the added return keyword to the onsubmit event. If the function called returns false the submit won't happen.
<form onsubmit="return ajaxMagic()">
<input type="text" name="partid" id="partid" />
<input type="submit" value="Find Part" />
</form
function ajaxMagic() {
...
return (false);
}
The solution I found for all of the browsers that I tested (IE, FF, Chrome, Safari, Opera) is that the first input type=submit element on the form has to be visible and has to be the first element in the form. I was able to use CSS placement to move the submit button to the bottom of the page and it did not affect the results!
<form id="form" action="/">
<input type="submit" value="ensures-the-enter-key-submits-the-form"
style="width:1px;height:1px;position:fixed;bottom:1px;"/>
<div id="header" class="header"></div>
<div id="feedbackMessages" class="feedbackPanel"></div>
...... lots of other input tags, etc...
</form>
This problem occurs in both IE and Chrome.
It does not occur on Firefox.
A simple solution would be to add the following attribute to the form tag:
onsubmit="return false"
That is, of course, assuming that you submit the form using an XMLHttpRequest object.
Yes, form with a single inputText field working as different in HTML 4.
onSubmit return false not working for me but the below fix bug is working fine
<!--Fix IE6/7/8 and HTML 4 bug -->
<input style="display:none;" type="text" name="StackOverflow1370021" value="Fix IE bug" />
I handled this by the following code but I am not sure if this a good approach.
By looking for input fields in a given form and if its 1 prevent the default action.
if($j("form#your-form input[type='text']").length == 1) {
$j(this).bind("keypress", function(event) {
if(event.which == 13) {
event.preventDefault();
}
});
}
I think that's a feature, which I did also disable it though. It's not taking big effort to disable it. Just capture the enter key, ignore it, will do.