Confused about forms and the submit button - javascript

I have a form like the following:
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST">
<div align="center">
<br><br>
<br><input type="submit" value="ABC" tabindex=0><br>
<br><input type="button" value="cancel"><br>
</div>
</form>
</body>
</html>
I would like the form to submit when the ENTER button is pressed and would also like the submit button to have have some color around it to show that it's default.
But it seems that I have to click the tab button to make the submit have blue around it as the default.
Is there some way to make it that the submit button is always the default and always shoes a blue circle around it to indicate this?
Also what if I have other input fields on the same html page but outside of the default. What I need is for the form to always submit when I press enter no matter where I am on that page. Is there some way to do this?

The submit should always be the default — whilst the form is focused, which is difficult here because you have no real input fields. What does this form actually do?
Further than that, don't override browsers' default UI behaviour: you'll just confuse your users.

For your enter-anywhere-submit, I would do it with jQuery. A lil bit of searching led me to this:
Submitting a form on 'Enter' with jQuery?

On forms, only the currently focused element has the blue outline, and this is typically a platform dependent feature.
That being said, you can customize that outline with a little bit of CSS to make the form look consistent across browsers:
form *:focus {
outline:2px solid blue;
}
Now, to make the submit button always show that outline, I would give it a class of "default":
<input type="submit" value="ABC" tabindex="0" class="default">
Then change the above CSS to include that class:
form *:focus, input.default {
outline:2px solid blue;
}
As for submitting the form on hitting enter: so long as an element in the form has focus, hitting enter will submit the form by default. If you want that to happen if the form doesn't have focus, you will need to use a little bit of JavaScript, but I don't recommend it, because as Tomalak says in his answer, you shouldn't change the browser's default behavior.

If you use Jquery you could attach an event handler to the tag HTML (or the document itself). Since events bubble up the DOM, this would intrecept it even if it is outside the form. Then, if the key pressed is RETURN, you submit the form.
$(document).keyup(function(event){
if (event.keyCode == 13){
$('form[name=myform]').submit();
}
});

Related

Two submit buttons, one is always hidden, how to hit enter and use the correct submit button

BEGINNING OF EDITED*** Updated function, however, hitting "enter" doesn't trigger the second submit button. Also adding this line of code:
document.getElementById('btn-default').removeAttribute("disabled");
in case the user wants to switch back to the original search button instead.
END OF EDIT ***
I have two submit buttons, the first one is the default for a general input search box. However, if the user clicks on the "Advance" link it will hide the general search input along with the submit button. And display the "Advance" submit button. When hitting enter it will default to the first submit button. Is there a way to detect when a submit button is hidden, to use the submit button that is displayed? Here is part of my code below:
FORM:
<form id='searchGroup' class='form-inline mt-2 mt-md-0' action='test.php' method='POST'>
<div class="col-md-5" id="defaultDisplay" >
<input class='form-control mr-sm-2' type='text' placeholder='' aria-label='Search' name='SearchAll' autofocus='autofocus'>
<!-- STANDARD SEARCH BUTTON -->
<input id='btn-default' class='btn btn-default my-2 my-sm-0' type='submit' name='SearchStd' value='Search'/>
</div>
<div class="collapse" id="collapseExample">
<!-- MULTIPLE INPUTS HERE -->
<!-- ADVANCED SEARCH BUTTON -->
<input class='btn btn-primary' type='submit' name='SearchAdv' value='Search'/>
</div>
</form>
FUNCTION to display div:
<script>
function switchVisible() {
if (document.getElementById('defaultDisplay')) {
if (document.getElementById('defaultDisplay').style.display == 'none') {
document.getElementById('defaultDisplay').style.display = 'block';
document.getElementById('btn-default').removeAttribute("disabled");
}
else {
document.getElementById('defaultDisplay').style.display = 'none';
document.getElementById('btn-default').setAttribute("disabled", "disabled");
}
}
}
</script>
One thing you could do is to just create two forms, one for basic search and one for advanced search. Then toggle the display between the two. It's a small, negligible redundancy that would fix this issue without resorting to JavaScript workarounds.
Alternatively, just use one form for both simple and advanced, and only having one submit button. Treat your form as an advanced form to begin with. A "simple search" would simply be an advanced search with empty advanced fields.
Any input or button on the form with TYPE="submit" will be linked to the ENTER key.
Notably in your case, if two such inputs have the TYPE="submit", the first one will be triggered on enter keypress.
One solution could be to set the DISABLED attribute on the one you do not want to trigger on ENTER keypress.
According to your requirement, you want the 'Advanced' submit button to be disabled to begin with, so edit your HTML to include the disabled property like this:
<input class='btn btn-primary' type='submit' name='SearchAdv' value='Search' disabled="disabled" />
Then, when you execute the code to show the 'Advanced' section, add the Disabled attribute to the 'default' section submit button:
document.querySelector('input[name="SearchStd"]').setAttribute('disabled','disabled');
while at the same time removing the DISABLED attribute from the 'advanced' section's button:
document.querySelector('input[name="SearchAdv"]').removeAttribute('disabled','disabled');
At this stage, I should mention I have noticed that your JavaScript code is working in a slightly different manner to how I understand your app to work:
It seems you are saying for each toggle "if the DEFAULT search is display block (shown), set display none (hide it), otherwise if it is not shown, show it"
I'm pretty sure you planned to be toggling the Advanced section, not the Default section (as the Default is shown by DEFAULT!). So assuming this is true and assuming you already made the HTML change mentioned above, AND assuming you've made a CSS change so that #collapseExample has display NONE to begin with... you'd want you JS like this:
<script>
function switchVisible() {
if (document.getElementById('collapseExample')) {
if (document.getElementById('collapseExample').style.display == 'none') {
document.getElementById('collapseExample').style.display = 'block';
document.querySelector('input[name="SearchStd"]').setAttribute('disabled','disabled');
document.querySelector('input[name="SearchAdv"]').removeAttribute('disabled','disabled');
}
else {
document.getElementById('collapseExample').style.display = 'none';
document.querySelector('input[name="SearchStd"]').removeAttribute('disabled','disabled');
document.querySelector('input[name="SearchAdv"]').setAttribute('disabled','disabled');
}
}
}
</script>
There are some ways to improve this by the way, for example you could look into "caching elements" so you don't have to repeat the getElementById's, and you could add IDs to the actual inputs which is considered good practice when manipulating unique elements, but to keep it simple and answer your actual question, this is my answer. Good luck!

Form submitting when clicking button that invokes javascript function to hide inputs [duplicate]

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>

Event listener for form submit in javascript with NO submit action

I have been building a chrome extension and I have been using content scripts to listen for the form submit event. I was testing my extension and it works pretty well, until I tested on a site that didn't work. The reason it didn't work is because the form button isn't really a form button with the submit action. It's actually an <a> tag with an href tag that links to "javascript:;", so the submit event doesn't trigger. The link is inside a form, it's just not a button tag with the submit action. How can I make sure that my content script triggers whenever a user tries to submit a form?
It seems simple at a glance, but there's no surefire way to achieve what you're asking.
Consider this:
document.getElementById('myform').addEventListener('submit', function(e) {
e.preventDefault();
console.log(document.getElementById('sometext').value);
console.log('form submitted');
});
document.getElementById('notasubmitbutton').addEventListener('click', function(e) {
console.log(document.getElementById('sometext').value);
});
<form id="myform">
<input type="text" id="sometext">
<input type="submit">
<button id="notasubmitbutton" type="button">Submit 2</button>
</form>
There's the regular submit button that will trigger the submit event. Then there's another button, that will just collect all the data from the form, but will not submit it in the traditional sense.
There's absolutely no way you could foresee all the possible ways someone could build their form, so what you're asking for can't be done.

IE clears input[type="file"] on submit

I have a page (demo):
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function() {
$("#id_button").click(function(e) {
$("#id_file").click();
});
});
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="http://www.google.com/">
<input type="file" name="file" id="id_file" />
<input type="button" id="id_button" value="fake button" />
<input type="submit">
</form>
</body>
</html>
if
I open browse dialog via clicking "fake button", select file (I see it in input[type="file"]), than click submit button and no post happens, the input[type="file"] is cleared.
What should I changed to get it work?
I get this problem in IE8 and IE10.
PS: file input will be hidden, so user will work only with fake button.
All of the browsers have different behavior when it comes to what they allow you to do from javascript with regards to programmatically clicking the input button for file inputs.
The best solution I have found that seems to work cross browser is to set the opacity to 0 (do not use display:none) and put the button underneath the input, so the user clicks through the 0 opacity input to your button, thus firing the input select dialog.
A good writeup on styling the file input can be found here: http://www.quirksmode.org/dom/inputfile.html
http://jsfiddle.net/j38Wj Works fine in Google Chrome but does not work in IE 10.
As I think IE does not allow select file by external 'click' event.
Only one way to "customize" input[type=file] is usage of opacity style to hide it and relative positioning of custom button control below it.
Working example: http://blueimp.github.io/jQuery-File-Upload/
[...]
I think all browser does that behaviour for security reason. When you submit a form, you are redirected to a different page(or the same page) and if you are directed to the same page, the form is re-initialized.
In this case, you simply can NOT set the value of file for security reason.
From example, How to set a value to a file input in HTML?, you don't want this happen
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:\passwords.txt">
</form>
<script>document.foo.submit();</script>
Add a label tag along with the input file element. Set the 'for' attribute of the label to the id of the input file element.
Then when you click on the label the input file element will 'click' and the file dialog will open.
Then simply style the label however you like. Have tried on various IE versions.

ie javascript form submit with file input

I have a html form, with a custom file upload field. And by that I mean that I have moved the actual file field beyond the borders of the page with css, that I have a custom input field and button in place, and that I have a jquery click event attached to that custom button to trigger the file input dialog.
It all works fine, in every browser.
But I need to submit the form through javascript. And I got somewhere that IE remembers my actions with javascript as a malicious manipulation of the file input field and blocks my access with an error "access denied" when I invoke document.formName.submit().
Is there a way around this, because I have gone completely mad by trying to search for a solution. I seriously don't want to use the default file input field, as every browsers renders it differently and messes up my design..
code:
<form name="thisForm" onsubmit="return false;" enctype="multipart/form-data" method="post" action="index.cfm/somepage">
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="text" name="shown" id="shown" />
<button id="button">browse..</button>
<input type="submit" id="submitForm" />
</form>
<script>
$('button').click(function(){
$('#shown').val($('#hidden').val());
});
$('submitForm').click(function(){
validateForm();
});
function validateForm()
{
//regular expression validation against all other input fields in the form
//not the file input field
validateVAT();
}
function validateVAT()
{
//connect to external service to check VAT
submitForm();
}
function submitForm()
{
document.thisForm.submit();
}
</script>
UPDATE:
I just tried to first upload the file, before submitting the form, through ajax, but that also gave me the acces denied error.. >_>
I was having the same problem, and I solved it by using a styled <label> tag with a slight workaround in Firefox.
http://jsfiddle.net/djibouti33/uP7A9/
The Goals:
allow user to upload a file by using standard html file input control
hide standard html file input control and apply own styling
after user selects file to upload, automatically submit the form
The Browsers:
Firefox, Chrome, IE8/9, Safari
IE7 didn't work, but it might if you add it to the workaround detailed below.
The Initial Solution:
Hide the file input by positioning it offscreen. Important not to display:none as some browsers won't like this.
Add another styled element to the page (link, button).
Listen for a click on that element, then programmatically send a click to the file input to trigger the native 'file explorer'
Listen for the file input's onchange event (occurs after a user chooses their file)
Submit the form
The Problem:
IE: if you programmatically send a click to a file input in order to activate it (2), programmatically submitting the form (5) will throw a security error
The Workaround Solution:
Same as above
Take advantage of the accessibility features built in to the label tag (clicking on a label will activate it's associated control) by styling
a label tag instead of a link/button
Listen for the file input's onchange event
Submit the form
For some reason Mozilla browsers won't activate a file input by clicking on it's label.
For Mozilla, listen for the click on the label and send a click event to the file input to activate it.
Hope this helps! Check out the jsfiddle for details on the html/js/css used to make it all work.
I found the answer myself, After 2 days of crazy trial&error. I hope I can help somebody with this..
I removed the hidden file input field from my coldfusion page and replaced it by an iframe tag. That iframe tag linked to another coldfusion page, containing another form with the removed file input field.
Now when I use javascript to click the file input field, which is still hidden from view, it still gives the browse file dialog without a hitch. But when I use javascript to submit the form, through the iframe, miraculously, it submits the form in the iframe, making it possible to upload the file in some serverside scripting of your preference.
iframe code:
<form id="formFileUpload" class="formFileUpload" name="formFileUpload" method="post" action="../actions/act_upload_file.cfm" autocomplete="off" enctype="multipart/form-data">
<input type="file" class="buttonFileHidden" id="inputFile" name="partnersLogo" />
</form>
iframe itself:
<iframe src="admin/dsp_file_upload.cfm" id="ifu" name="ifu" class="buttonFileHidden">
</iframe>
javascript click & submit:
ifu.document.formFileUpload.partnersLogo.click();
ifu.document.formFileUpload.submit();
If you're like me, and you don't want to use an iframe, and you weren't too keen on the label solution mentioned above, you can just position the original button above the styled button with an opacity of 0.
Using the example above, you would still have:
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="button" name="shown" id="shown" value="Add File" />
But .hidden would be defined like so:
.hidden {
position: absolute;
left: -150px;
opacity: 0;
filter: alpha(opacity=0);
}
Config: Set the opacity to 0.5 (or =50) to see the transparent element and tweak the left positioning.
Arguably just as hacky as the answers above, but a bootstrap-friendly solution, and in my case, the only one that worked.
I found a weird solution to solve this problem.
It thought about the js click thread. If it goes out of this thread, there no more security issues.
I chose to use window.setTimeout. see sample below:
<script type="text/javascript">
$(function () {
$("#<%= this.fuDoc.ClientID %>").bind('change', uploadFile);
$("#<%= this.btnUpload.ClientID %>").click(chooseFile);
});
function chooseFile() {
$("#<%= this.fuDoc.ClientID %>").click();
}
function uploadFile() {
var fu = $("#<%= this.fuDoc.ClientID %>");
if (fu.val() != "") {
window.setTimeout(function () {
<%= this.ClientScript.GetPostBackEventReference(this.btnUpload, "") %>;
}, 100);
}
}
</script>
<asp:FileUpload ID="fuDoc" runat="server" style="display: none;" />
<asp:Button runat="server" ID="btnUpload" Text="upload" OnClick="btnUpload_Click" />
<asp:Label ID="lbltext" Text="" runat="server" />`
then, no more acces denied!
This is an old post but the problem still arises. This may not be working because jQuery kindly fails silently. I was having this problem and wondering why my hidden form would not submit and the file get uploaded. I started off by using jQuery, but then I went vanilla. It still didn't work but looked as though an exception was being thrown in my .click() function.
Running
try {
document.getElementById('formid').submit();
} catch (e) {
alert(e);
}
showed that we indeed were throwing an error, and quick research showed that this was because IE DOES NOT SUPPORT SIMULATED CLICKS ON A FILE INPUT. This means that when the form went to be posted, IE would refuse to post the form
Excuse the bold caps, but I know many people will see text and not read it
Have you tried
$('button').click(function(){
$('form[name=thisForm]').submit()
});
You need to change onsumbit='return false;' to onsubmit='return validateForm()'.
Then have validateForm() return true if the form passes your validation checks, or false if it does not.
The onsubmit='return false' is preventing the form from submitting via document.thisForm.submit(); as well as when the user clicks the submit button.
I commented these lines in j query.form.js then every thing works fine for me. Don't ask me the reason even i don't have the solution for that but it works for sure.
if (io.contentWindow.document.execCommand) {
try { // #214
io.contentWindow.document.execCommand('Stop');
} catch(ignore) {}
}

Categories

Resources