We have a couple of textboxes in a form. All of which are validated onblur. The form is submitted onclick of an anchor tag.
<script>
function validateMyText(){
// do field validation
// if success
return true;
// else {
alert("Please check the text box value");
return false;
}
}
</script>
<form name="myform" action="mytestpage.jsp">
<input type="text" name="myText" id="myText" onblur="return validateMyText()"/>
Submit
</form>
Windows platform browsers (Firefox, Safari, Chrome, IE): When validateMyText() returns false, onclick is not triggered. This is the expected and existing behaviour.
Mac platform browsers (Firefox, Safari): Even after validateMyText() returns false, onclick event is triggered, which submits the form.
Background: This is a legacy application that was supported only on Windows platform and IE browser. Now it has to be enhanced to work on all the browsers (Firefox, Safari, Chrome, IE) on Windows and Firefox, Safari on Mac.
If I read this correctly, it looks like the app is relying on the false returned after the blur event of any field with "invalid" data to interrupt the form submission. Baked in, then, is the assumption that any other field that is not focused is valid, you cannot leave a text field without making it valid, and that the only way you'd ever be clicking the anchor tag is while leaving a previously selected text field. A lot of assumptions. The kindest thing to say is that it's brittle -- and what about users hitting Enter?
At minimum, I would create a new function to handle form submission. I don't know what's going on in that anchor tag right now. For clarity, add an ID to your form tag. Then:
<a href="#" onclick="document.getElementById('myform').submit(); return false;">
Now the default click will be suppressed, and you'll run the "natural" submit behavior of the form. Since we want validation before submission, let's add an onsubmit event handler at the form level:
<form name="myform" id="myform" action="mytestpage.jsp" onsubmit="return submitForm();">
Now we'll run through a form-level validation, and return true for submission, false for none. Add something like this to your JavaScript:
function submitForm() {
// identify fields eligible for validation
// validate them according to your rules
// then submit the form
if( all_your_fields_are_valid ) { // for you to figure out
return true;
} else {
// dialog explaining problem?
// highlight bad fields?
return false;
}
}
You'll still have your field-by-field warnings of invalid data, but now at least you're trapping the form submission explicitly, and looking at the form as an entity with its own overall valid and invalid states. A setup like this should work fine in any reasonably modern browser on any platform.
All that being said, I'd highly recommend adding one of the great JS frameworks. They'll make things much easier, especially if you're looking to clean up and graft behaviors onto lots of existing code.
Related
My question is about react, onSubmit and preventDefault.
I've got a form, which handles between 2 - 4 steps of user input depending on certain cases.
<Form>
{StepRendersHere}
</Form>
The form has a onSubmit event that prevents default (and stopPropagation).
When using the button for "next step" the event fires, and the form is NOT submitted.
But when using the enter key, the event is fired, but the form is posted. This results in the site refreshing with the form data as url parameters.
The weird thing is that if none of the buttons in the form has type="submit". The onSubmit doesn't even fire on enter key.
isDefaultPrevented returns true in both cases.
Any hints/thoughts on how I can prevent the form from posting when pressing enter? My issue is with Enter key posting the form, despite preventDefault.
Have tried binding the enter key to a event that prevents default, doesn't work. Might have done it the wrong way though.
UPDATE (implementation)
<Form onSubmit={this.inc_step} id="applicationform">
{FormStepRenderedHere}
</Form>
inc_step = e => {
e.preventDefault();
e.stopPropagation();
alert( e.isDefaultPrevented() )
let new_step = this.state.current_step + 1;
alert('INSIDE INC STEP');
if (this.validateForm()) {
this.setState({
current_step: new_step
})
}
}
UPDATE (FIXED IT)
I found a solution, and want to share if anyone else has the same problem.
My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.
Thank you for the comments!
A much easier way to accomplish this is to add a button element to your form and add the display none css attribute (if you don't want to see the button).
The button automatically adds the ability to use the enter key with onSubmit.
I found a solution, and want to share if anyone else has the same problem.
My solution however might be unique to semantic ui, which i'm using. I solved it by putting as={Form.Group} on the form, mening it wont render as a form, with its standard events, such as enter key submit. Now the enter key does nothing, as I wanted it.
So actually not rendering the form as a form to begin with was the solution.
Is there a way to link a button to an input, so mobiles know what to do when you press Next or Go on the keyboard within a .NET context (i.e. Pressing 'Go' on an input fakes the click on the next button instead of submitting the form)?
Let's talk code for a second. I have the following markup, where injected-via-js is injected via javascript into a large form (progressive enhancement).
<form class="dotNET-form-wrapper">
<div class="injected-via-js">
<div>
<span>£</span>
<input type="number" />
</div>
<div>
<button>accept</button>
</div>
</div>
<!-- More form elements -->
</form>
On most mobile browsers, when you change the value in the number input and press Go or Enter it fakes the button press (which in my case has an important event bound to it). However on some old Android devices pressing Go will submit the form instead, which is not what I want. To clarify: I want the Go button to fake the button press, not submit the form.
Note:
.NET is only relevant to this question due to the fact that everything is wrapped in a form, meaning I cannot create a separate form around the input and button and highjack the new form's submit.
I've made a JSBin where I was able to replicate this bug with an Android 2.2 phone although I imagine it exists on other bad browsers as well. It works as expected on iOS 6+ and Android 2.3+.
Here's the demo page: http://jsbin.com/tebizoda/2
And here's the edit version: http://jsbin.com/tebizoda/2/edit
Both "Go" and "Enter" has keycodes like the enter on the keyboard (13) so you should just make a JavaScript or jQuery function that overrides the default behaviour and just triggers the button press. Something like (example in jQuery):
$(your_form_or_input).keypress(function (e) {
if (e.keyCode == 13) {
return false;
} else {
// your code here...
}
});
Mind that some browsers use e.keyCode, others e.which to determine the pressed key code.
I have a text field which will accepts only numbers. When the user types any characters and moves out of the textfield,
using onchange I am checking whether user have entered Number or characters. So when user press tab , using onchange the value is checked.
When the user press Enter button, it is set as window.event.keycode =9; as IE supports this. To make it work in other browsers,
I have written logic to move the focus whenever the user presses the enter button.
The problem which I am facing is in Firefox, when the user presses enter button in the text field, now onchange is called as well as onsubmit is also called, which makes my page to refresh again.
The logic which I have written to move the focus to next item , is also working. But I don't know why, onchange and onsubmit is called.
This project composes of huge amount of code, thats why I am not able to post a piece of code.
Any idea why it is working like this?
Some browsers have a global event object, other send the event object to the event handler as a parameter. Chrome and Internet Exlporer uses the former, Firefox uses the latter.
Some browsers use keyCode, others use charCode.
Enter key code is 13
function Numberonly() {
var reg = /^((\d{1,8}(\.\d{0,5})?%)|(\d{1,8}(\.\d{0,5})?))$/;
if (!reg.test(($("#txtunitId").val()))) {
$("#txtunitId").val('');
return false;
}
}
<input type="text" id="txtunitId" style="float: left;" onkeyup="Numberonly();" />
jsfiddle.net/hQ86t/20
I have a search form:
<form class="searchForm" id="topSearchForm" action="/search.ds">
that has an onsubmit-event attached to it, triggering a javascript. The purpose of this javascript is to empty certain form-fields before submission of the form based on certain criteria.
To be clear, what needs to happend is:
User input -> User clicks search button (or presses "enter") -> Javascript runs -> fields are cleared -> form is submitted
This works exactly as intended in all browsers except in IE7 and IE8. The javascript runs but for some reason the form submission is done before the fields are being cleared by the javascript. This causes the submitted page to include the data from fields that were supposed to be cleared.
I only have control of (certain parts of) the UI and cannot handle anything after the submission of the form. For usability purpose it is important that these fields (that should be cleared) are filled out up until the user submits the form.
Why is the internal logic different in IE7 & IE8 (it works fine in IE9 and "all other browsers)? Is there a way for me to circumvent this issue?
Here are some more code to clarify:
I attach the event to the form:
var formElement = document.getElementById("topSearchForm");
[...]
formElement.attachEvent('onsubmit', function() {clearForSubmit()});
and clearForSubmit is defined and is triggered.
You can try something like this in the js
<form onsubmit="clearForSubmit(); return false;">
this will NOT submit the form, you can submit the form after you clear it with
form_name.submit();
Use an onclick event instead of onsubmit, then submit the form at the end of the function in code.
I am looking for the neatest way to create an HTML form which does not have a submit button. That itself is easy enough, but I also need to stop the form from reloading itself when submission-like things are done (for example, hitting Enter in a text field).
You'll want to include action="javascript:void(0);" to your form to prevent page reloads and maintain HTML standard.
Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.
Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?
Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:
onKeyPress="if (event.which == 13) return false;"
For example:
<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
an idea:
<form method="POST" action="javascript:void(0);" onSubmit="CheckPassword()">
<input id="pwset" type="text" size="20" name='pwuser'><br><br>
<button type="button" onclick="CheckPassword()">Next</button>
</form>
and
<script type="text/javascript">
$("#pwset").focus();
function CheckPassword()
{
inputtxt = $("#pwset").val();
//and now your code
$("#div1").load("next.php #div2");
return false;
}
</script>
When you press enter in a form the natural behaviour of form is to being submited, to stop this behaviour which is not natural, you have to prevent it from submiting( default behaviour), with jquery:
$("#yourFormId").on("submit",function(event){event.preventDefault()})
Two way to solve :
form's action value is "javascript:void(0);".
add keypress event listener for the form to prevent submitting.
The first response is the best solution:
Add an onsubmit handler to the form (either via plain js or jquery
$().submit(fn)), and return false unless your specific conditions are
met.
More specific with jquery:
$('#your-form-id').submit(function(){return false;});
Unless you don't want the form to submit, ever - in which case, why
not just leave out the 'action' attribute on the form element?
Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.
If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.
Try preventDefault() method inside event listener for submit in this form