Android Keyboard not hidden after form submit - javascript

You create a form with the input field and "Clear" button and you expect that:
When you type something and hit "Go/Search" button on mobile keyboard the keyboard should be hidden.
And when you click on "Clear" button the input should be cleared but keyboard stays open.
Funny thing is that it works totally opposite: the keyboard would be opened after submitting the form and disappear after cleaning the input.
Is there any way to make it "right"?
The code, HTML
<form id="form">
<input id="input" type="search" autofocus />
</form>
<button id="clear">clear</button>
and JS
document.getElementById('form')
.onsubmit = function(e) { e.preventDefault() }
document.getElementById('clear')
.onclick = function(e) {
e.preventDefault()
var input = document.getElementById('input')
input.value = ''
// trying to focus to open keyboard, but it didn't work
input.focus()
}
Demo https://codepen.io/anon/pen/rpGjGe?editors=1011

I see how you could see it that way, but it's a matter of how certain events work by default in JS.
When you click on your "clear" button, what you are doing is focusing out of your input, which in turn is what makes the keyboard disappear. Since you are no longer typing on your input, the keyboard goes away.
However, when you click on "Go/continue/submit" button, the focus remains on the input until the correspondent form action triggers.
I would either:
Force the focusout event on the input on submit, and focusin on the input after clicking on "clear", same as you are doing now; OR
Add a submit button to trigger the form submit event. That would remove the focus off the input and place it on the submit button.
Below is a code snippet for Option 1:
document.getElementById('form')
.onsubmit = function(e) { e.preventDefault(); }
document.getElementById("form").onsubmit = function(e) {
e.preventDefault();
document.getElementById('input').blur();
};
document.getElementById('clear').onclick = function(e) {
e.preventDefault();
var input = document.getElementById('input');
input.value = '';
input.focus();
};
<form id="form">
<input id="input" type="search" autofocus />
</form>
<button id="clear">clear</button>
See this CodePen for reference.

Related

HTML text box and button that redirects user to a page of same name not working when <form> is added

Below is a code that redirects people to a page of the same name. For example, if I type in the word 'chocolate' and click 'Submit', the user should be redirected to a page of the same name called 'chocolate.html', etc.
This code only works when the <form> parameter tag is removed, and if removed involves manually clicking the [Submit] button to be redirected to the .html page of the same name (rather than redirecting when pressing [Enter] or [Return] key on the keyboard).
This code does not work when I add the <form> parameter tag; it only works if removed. I've been meddling with this for hours to get it to work with the <form> tag. Any ideas?
This is the code:
Note: If you remove the form tag, it works, but only when you click the 'Submit' button manually.
This is what I got so far, I now only need the button to automatically click when the person presses the Enter key on their keyboard. :)
UPDATE: Firstly, thank you so kindly for your help so far.
UPDATE: The code now successfully redirects to a .html page of the same name, but the user needs to manually clicks the [Submit] button to accomplish this. From here, I am simply needing to find a way of having the [Enter] button automatically be selected/clicked whenever the user presses [Enter] on their keyboard. :)
<input id="test" type="text" autofocus>
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
</script>
Add a type attribute to your button like so:
<button type="button" onclick="redirect()">Submit</button>
By default, if not set, the type of a button is assumed to be submit and will therefore submit your form to the action provided in the form's action attribute. Setting the type attribute to button prevents this default behaviour.
Seeing that you have no action attribute specified in your form, the current page is assumed as the action to redirect to so the form essentially reloads the current page.
This is something new. Anyway the thing is when you are keeping the form tag there it is with no action attribute keeping you in the same page. When form tag is there you can not hit the script for the redirect.
When you are removing the form tag it is hitting the JS and activating the code. Seeing the form tag I am assuming that you are trying to send some data.
It is advised that you use jquery and ajax to manipulate these data. Or you can discuss more.
Add this after your function:
var test_keydown = document.getElementById("test");
test_keydown.addEventListener("keydown", function (e) {
if (e.code === "Enter") { //checks whether the pressed key is "Enter"
redirect();
}
});
I got your problem, basically, you want to trigger redirect function when the user clicks submit button or if the user presses the ENTER key on the keyboard.
You can do this 2 ways -
If you want the user to redirect when he press enter key anywhere on the page, then you need to add keyup event on the document object, see below code -
It will trigger redirect function when the user clicks the ENTER key on the keyboard.
<input id="test" type="text" autofocus>
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) { //13 is enter keycode
event.preventDefault();
redirect();
}
});
</script>
Another way is to add keyup event on the input itself and then call the redirect function. This is when you don't want to trigger redirect on the whole document, but only when the user is done typing in input and then presses ENTER.
<input id="test" type="text" autofocus onkeyup="handleKeyUp(event)">
<button type="button" onclick="redirect()">Submit</button>
<script>
function redirect()
{
var url=document.getElementById('test').value
window.location = url+".html"
}
function handleKeyUp(event) {
if (event.keyCode === 13) { //13 is enter keycode
redirect();
}
}
</script>
If you want to do this in form tags handle the on submit event instead. This will also handle the enter keypress at the same time as that is the default behavior in a form.
//Add the evnent listener unobtrusivly
document.getElementById("redirector").addEventListener("submit", function(event) {
//Stops the form submitting (its' default action)
event.preventDefault();
//Get the location
var redirectTo = document.getElementById('test').value + ".html"
//bit of debugging
console.log("Redirecting to: " + redirectTo)
//redirect
window.location.href = redirectTo;
})
<form id="redirector">
<input id="test" type="text" autofocus>
<!-- Note this will now submit -->
<button>Submit</button>
</form>
You should use
document.addEventListener('keyup',function(e) {submitButton.click()})// submitButton is `document.getElementById('<idOfsubmitButton>')`

Prevent onclick event on a button from firing when hitting Enter in a different box

I need to have a user input field in the #wmd-button-bar of the SE editor, along with a button. The user can enter some data in the input field, and then press a button to process that data. I am using a userscript to achieve this. I have created a separate MVCE of that, and here is its direct install link for Tampermonkey/Greasemonkey.
To reproduce the issue, install the userscript. Reload this page and then click "Edit". You'll notice a new blank input box with a button. Focus the the "Edit summary" box blank, leave it blank, and hit Enter. Instead of submitting the answer box, your caret will now instead focus on the new blank input box.
The same happens if you press Enter inside the "Question title" box.
From the console.log messages, you'll notice that there has been instead a MouseClick event on the button! This is not expected behavior. In fact, how is this even possible? We just pressed Enter inside the Edit summary box, and didn't even touch either the new blank input or its button. How did it then register a mouse click?
How to fix this?
Note: The e.preventDefault(); inside the button onclick handler is necessary. Otherwise, when the user presses the button to process their input data, the answer box submits itself instead.
The Userscript Code:
function createModal(buttonBar){
var div = document.createElement("div"),
input = document.createElement("input"),
btn = document.createElement("button");
div.id = "box";
input.type = "text";
btn.innerHTML = "Button";
btn.onclick = function(e){
e.preventDefault();
console.log("I was called");
input.focus();
console.dir(e);
console.trace();
};
div.appendChild(input);
div.appendChild(btn);
return div;
}
setInterval(function () {
var cont = document.querySelector(".wmd-container:not(.processed)"), ul, buttonBar, div;
if (cont && (ul = cont.querySelector(".wmd-button-bar ul"))) {
cont.classList.add("processed");
buttonBar = cont.querySelector("div[id^=wmd-button-bar]");
div = createModal(buttonBar);
buttonBar.appendChild(div);
}
}, 500)
Its default HTML behaviour. All the buttons inside a form are of type="submit". On pressing enter, the most recent button of the form is clicked and their handlers are called, by default. To fix this, the buttons are created with type="button".
console.log(document.querySelector("#a").type)
console.log(document.querySelector("#b").type)
console.log(document.querySelector("#c").type)
<form>
<input type="text">
<button id="a" onclick="console.log('a')">Submit type</button>
<button id="b" onclick="console.log('b')" type="button">Button type</button>
<input id="c" type="submit" value="Input Submit type">
</form>
You can refer this to understand the behaviour of <button> and <input type="button">.
If you just check in console like, document.querySelector("#box").children[1].type it will show as submit.
Button, by default, acts as submit type unless it is specified explicitly (either submit(default)/reset/button). Just run document.querySelector("#box").children[1].type=button. You find it working as expected.
The behaviour is same in cross-browser and tested in Firefox Nightly (developer version), Chrome and Safari and works a little bit different in IE.
Also you can see the click is by default by seeing console.log(event.detail) is 0 as it is triggered internally. When triggered with a left click, it would be 1. MDN Docs on click event
The short and simple answer, is to force type for your button element:
<button type="button"></button>
It defaults to type="submit", and that's why it acts accordingly.
i tried the following code in firefox browser and it works as expected.
function createModal(buttonBar){
var div = document.createElement("div"),
input = document.createElement("input"),
btn = document.createElement("button");
div.id = "box";
input.type = "text";
btn.type = "button";
btn.innerHTML = "Button";
btn.onclick = function(e){
console.log("I was called");
input.focus();
console.dir(e);
console.trace();
};
div.appendChild(input);
div.appendChild(btn);
return div;
}
setInterval(function () {
var cont = document.querySelector(".wmd-container:not(.processed)"), ul, buttonBar, div;
if (cont && (ul = cont.querySelector(".wmd-button-bar ul"))) {
cont.classList.add("processed");
buttonBar = cont.querySelector("div[id^=wmd-button-bar]");
div = createModal(buttonBar);
buttonBar.appendChild(div);
}
}, 500);
notice that i have set the btn.type="button"; this makes sure the form is not submitted and also removed e.preventDefault(); as button will never submit the form now.
keep in mind that by default if you don't give a type to a button element then it will behave like a submit button.
also the MouseClick event was firing because the click event is triggered on submit buttons present within the form when submitting the form. as you had the button without the type attribute it was working like a submit button. so the MouseClick event was fired when you hit enter (as its submitting the form).
you can verify this by adding an onclick handler from your browser developer tool to the Save edits submit button and hit enter on the text field.

Exclude form button from 'onblur' event, JavaScript

I have a form that uses onblur for most of the input fields, like follows:
<form>
<input name="..." id="..." onblur="myFunction(name)" />
<button id="..." onclick="submit()">Submit</button>
</form>
The form validates certain fields (i.e. username, email) in real time via the onblur events, but the same check happens when the user clicks the submit button.
Currently, when the user clicks the submit button, the onblur event is first triggered, and then the onclick event from the button is triggered - thus running the check twice and wasting a couple extra seconds.
Is there any way to override the onblur method to exclude the blur that happens when the user presses the submit button?
I was thinking a simple if(/*button is clicked*/){} within myFunction(), but I wouldn't know how to check for the button click. And it seems, based on the current performance, that the button click is not even registered until after the blur.
Thanks in advance.
You could do this:
HTML
<form>
<input type="text" name="name" id="id" />
<input type="submit" />
</form>
jQuery
$(document).on('blur', 'input:not([type="submit"])', function(e) {
var key = e.keyCode; // the key pressed
var elem = e.target; // the element blurred
myFunction(name);
});
$(document).on('click', 'input[type="submit"]', function() {
submit();
});

Form Submit Not Triggering When Modifying Form In focusout Handler

I have tried to boil this down to a simple example to demonstrate what I'm running into.
I have a form with an input field and a submit button:
<form id="focusOutAfterInputForm">
<input type="text" id="focusoutAfterInput">
<input type="submit" >
<div></div>
</form>
The input field has a focusout handler attached that inserts a new element below the input:
jQuery("#focusoutAfterInput").focusout(function() {
jQuery(this).after("<div>message</div>");
});
I have also attached a submit handler just to capture if the submit is run:
jQuery("form").submit(function() {
jQuery("#console").append("<li>submitted form" + this.id + "</li>");
return false;
});
If the cursor is placed into the input and the submit button is clicked, the submit handler does not fire. If the submit button is clicked a second time it will fire. Also, if the field is blur'ed and then the submit button is pressed it will fire.
However, if instead we insert the new element below the div in the form, the submit button will fire even though the element is inserted:
<form id="focusoutAfterDivForm" novalidate="novalidate">
<input type="text" id="focusoutAfterDiv" required="true">
<input type="submit" >
<div></div>
</form>
jQuery("#focusoutAfterDiv").focusout(function() {
jQuery(this).parent().last().after("<div>message</div>");
});
Here is a jsfiddle demonstrating the code. I'm a bit baffled. Ideas anyone?
The problem doesn't seem to be that submit isn't executed, but rather the click event isn't executed on the button, because the mouseup isn't on the submit button once the div is inserted. If you use tab and space in your fiddle it works. Also if you add the element in a way that the submit button doesn't move, it works:
jQuery("#focusoutAfterInput").focusout(function() {
jQuery(this).next().after("<div>message</div>");
});
or in this example: http://jsfiddle.net/K9vrW/3/

test whether button being clicked before running function on element.blur()

I have a function called showHide() that alternately shows and hides a text input field and a button (button2) when another button (button1) is clicked. The text input field is automatically focused when it opens, and this works great.
The HTML looks roughly thus:
<button1>Show/Hide</button>
<form>
<input class="hidden" type="text" />
<button2 type="submit">Submit</button>
</form>
<script type="text/javascript">
$("button1.someSelectors").click(function() {showHide();});
$("input.someSelectors").blur(function() {showHide();})
</script>
I would like to extend the function such that when the input field loses focus it and button1 disappear, unless it loses focus because button1 is being clicked. As it reads now I'm only testing whether the input field has focus or not. How can I also check whether button2 is being clicked or not?
I tried:
$("input.someSelectors").blur(function() {
if (!$("button2.someSelectors").is(":focus")) {
showHide();
}
});
but it hid the form elements even when I tried clicking button2.
An alternative would be to test whether button2 is being clicked or not in the "hide" part of the function, but when I added
if(!$("button2.someSelectors").click()) {do the hide part of the function}
to showHide(), the form got submitted when I clicked button1 or button2. Here is an example of my problem. Can anyone help?
--Edit:
var showHide=function(item, category) {
if($("input."+item+"."+category).hasClass("hidden")) {
$("input."+item+"."+category).show("fast").focus().removeClass("hidden");
$("button.buy."+item+"."+category).show("fast");
$("button.purchase."+item+"."+category).text("Never mind!");
} else {
$("input."+item).hide("fast").addClass("hidden");
$("button.buy."+item).hide("fast");
$("button.purchase."+item).text("Purchase");
}
}
blur event on textbox is triggered before the click event fires on the button. In order to avoid that you can use mousedown event instead of click event which will be triggered before click event. Try this
$("button1.someSelectors").mousedown(function() {showHide();});
$("input.someSelectors").blur(function() {showHide();})

Categories