IE not triggering keyboard event on a form with ONE FIELD - javascript

I'm seeing my Friend's code here...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Check action </TITLE>
<script>
function detectEvent(){
if(window.event.keyCode==13)
{
alert("you hit return!");
}
}
</script>
</HEAD>
<BODY>
<form name="name1" onkeyup="detectEvent()" action="page2.html">
<p> Field1
<input type="text" id="text1"/>
</p>
</form>
</BODY>
</HTML>
and when he tried entering a value in the textbox and pressed enter, it did not call the detectEvent(). I said, it'll always call onSubmit on enter button.....
and he surprised me,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Check action </TITLE>
<script>
function detectEvent(){
if(window.event.keyCode==13)
{
alert("you hit return!");
}
}
</script>
</HEAD>
<BODY>
<form name="name1" onkeyup="detectEvent()" action="page2.html">
<p> Field1
<input type="text" id="text1"/>
</p>
<p> Field1
<input type="text" id="text2"/>
</p>
</form>
</BODY>
</HTML>
Now press enter, The function gets called.....
Why so!?
Why onKeyUp not called on forms with just one field.!!! am i missing something?

The order of events is:
keydown
keypress
submit
keyup
So by the time your keyup handler would have been called, the form has already started submitting. If the action of the form is a page2.html on the local filesystem, that's going to navigate very quickly and probably move away from the page before keyup can be called; set the action to an external site, on the other hand, and keyup will have time to fire.
Adding the second input field is a different issue: in this case the form is not submitted at all. It is a curious historical quirk that browsers will submit a form that has only one input and no submit button, but refuse to submit a form with more than one input, and no submit button. This goes back to the HTML 2.0 spec:
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.
HTML 2.0 didn't specify whether or not Enter should be accepted to submit a form in any other circumstances (the intention seems only to have been to duplicate the functionality of the ancient <isindex> element), but browsers of the day seem to have interpreted that to mean that Enter-submission shouldn't happen where there are multiple fields, but then any submit button causes Enter-submission to happen anyway. IE and other later browsers copied this odd behaviour.
Unrelated point: the reliance on window.event makes the code needlessly IE-only. For all other browsers, the event object is passed in as an argument to the event handler function. You can do onkeyup="detectEvent(event)" in the HTML and then use that argument in the detectEvent function, which works on both models because either the local argument event or the global window.event is used. But the usual approach would be to lose the event handler attribute and assign from JavaScript:
<form action="page2.html" id="enterform">
<p> Field1
<input type="text" id="text1">
<!-- Note: *no* trailing slash - the doctype says HTML4, not XHTML -->
</p>
</form>
<script type="text/javascript">
document.getElementById('enterform').onkeyup= function(event) {
if (event===undefined) event= window.event; // for IE
if (event.keyCode===13)
alert('You pressed Enter');
};
</script>
Having said all that... I'm generally suspicious of trapping the Enter key. I'm not quite sure what you're trying to do, but if it's the common case of changing the default button in a form this definitely isn't the way to do it and will cause an assortment of problems. There is no good reason you should be trapping the Enter key to call .submit() on a form.

Interestingly enough, in Google Chrome, the form with the second input field will still submit, so it never catches the enter key on a keyup event, regardless of how many fields you have.
Solution = use keypress or keydown.

Related

Can a DOM element handle both keyup and input event?

In an application I have a text input elements with an input handler. There is a special action I'd like to do on backspace so I added a keyup handler to handle this case. It doesn't gets called unless the field is empty - apparently when the input handler is called it suppresses the keyup handler.
I could probably rewrite the code using the keyup handler for everything but that would involve reproducing proper handling of pasting and other keys (delete, enter, tab, etc.), which I'd rather not do.
This is on chrome but I tested it on firefox and safari too and get the same behavior so it must be expected, but I can't find it documented. The following code demonstrates the issue. When loaded as is and text is entered only the input handler is called. When the field is empty the keyup handler is called. If the input handler is deleted then of course the keyup handler is called on every key press.
<html>
<head>
<script>
function setup() {
document.getElementById("xxx").addEventListener("input", (ev) => alert("input"));
document.getElementById("xxx").addEventListener("keyup", (ev) => alert("keyup"));
}
window.addEventListener("load", () => setup());
</script>
</head>
<body>
test handlers: <input type="text" id="xxx" />
</body>
</html>
(sample edited to use addEventListener rather than onevent)
The workaround I'm thinking about now is using a keydown event, which is called, but I'd like to understand why it has this behavior.
They are both getting called every time only the one alert is invalidating the other call as you can see if you change the alert to a log
<html>
<head>
</head>
<body>
test handlers: <input type="text" oninput="console.log('input')" onkeyup="alert('keyup')" />
</body>
</html>
or if you set a timeout
<html>
<head>
</head>
<body>
test handlers: <input type="text" oninput="setTimeout(()=>alert('input'),1000)" onkeyup="alert('keyup')" />
</body>
</html>
This is expected as a backspace is changing the input and a keyup is when a key is released and the keyup is released when the alert is in the window

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>

How to fill in input with "require" using javascript?

I am new to java script. I have created an input which is requires the user to input some text to enable the submit button.
<input class="param" name="test" id="test" required ng-model="test">
How can I fill in the input text box using Java Script so I can submit the form (as if the user has entered the text). Currently, when I use for example the following script to update the value, the submit button on the form is not active.
document.getElementById("test").value =1
Could you update the attribute that ng-model is bound to? That should apply the value to the text field correctly.
I have created this example code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function updateValue() {
document.getElementById("test").value = 'test';
}
window.onload = function () {
updateValue();
}
</script>
</head>
<body>
<form action="" method="post">
<input type="text" id="test" name="test" required>
<input type="submit" value="Okay">
</form>
</body>
</html>
This is what Phani Kumar M and Claies were asking for. I tested it on Windows 10 in Firefox 55.0.3 and Chrome 60.0.3112.113. In both browsers it works correctly. The form can be submitted without adding anything to the field.
Others can check other platforms. As mentioned, the required attribute will not work in Safari.
Your problem is somewhere else. I don't know anything about AngularJS, which you seem to be using without even mentioning it, but it might be there.

Error in html file with Javascript onBlur event

I'm reading a tutorial of Javascript, I'm making a html file with a javascript function with a box, the fact is that the alert does not show what goes into the text field, what am I doing wrong ?, this is my code. I'm not entirely clear, how it handles the event onBlur, someone explain more about it? as in the tutorial the only explanation they give is "Losing the focus control," I don't know what they mean by the word focus, or how it is handled the text box, without enter botton.
<html>
<head>
<script>
function show ()
{
var age= parseInt (cage.value);
if (age<=18)
alert("access denied");
else
alert("Welcome");
}
</script>
<title> New Page I </title>
</head>
<body>
Age:
<input type="text" id "cage" name="cage" size="10"
onBlur=show();>
</body>
</html>
The onBlur event fires when the current control loses focus. When a control has focus, meaning that it's currently "selected", things that can cause it to lose focus include clicking on another control or pressing the tab key.
The reason your method does not work properly is because it has a small error. Try this:
<html>
<head>
<script>
function show(el)
{
var age = parseInt(el.value);
if (age<=18)
alert("access denied");
else
alert("Welcome");
}
</script>
<title> New Page I </title>
</head>
<body>
Age:
<input type="text" id="cage" name="cage" size="10" onBlur="show(this);" />
</body>
</html>
You have to use () after function name and look up the element first and then retrieve the value from it.. here is sample code.. (should work, not tested)
function show(){
var age = document.getElementById('cage').value;
if (parseInt(age, 10)<=18)
alert("access denied");
else
alert("Welcome");
}
the onBlur event is fired when you click on anything other than the input box (e.g. clicks another one, or click on a link to something). Basically, if you can't type in the input field, it does not have focus.
As for why it's not working, see #Teja Kantamneni 's answer, which should make it work.
You can getting an error because you are missing the parentheses() after the function declaration. Even if you have a function with no parameters must include the parentheses () after the function name.
Focus is when a form element receives control, so you can type in it or change options of a dropdown. Like onBlur there is also an onFocus event.
Focus is generally set on page load. so when the page is loaded so user does not have to go and click on the first field they need to fill in.
In this example you can have:
Javascript
function setFocus(){
document.getElementById('cage').focus();
}
HTML
<body onLoad="setFocus();">

Confused about forms and the submit button

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();
}
});

Categories

Resources