Exclude form button from 'onblur' event, JavaScript - 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();
});

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>')`

Having issues with setting an even listener to prevent default in input field with javascript

I am trying to make a simple password generator and i want the password generation to happen on the click of a button and that part works when i test it in the console. And now to implement it on sort of a real web page, the password generated to the input field doesn't stay!!, i know to use the .preventDefault() method but i don't know hot to apply it in this case using an event listener for when the value of the input field changes.
I couldn't add the html because it looks strange when i add it, but it looks like this:
Password: <input type="text" name="password" id="password" value="">
<button id="button" onclick="makePassword()">Get password</button>
here is my code below:
var capitalAlphabets=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var smallAlphabets=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var numbers=[1,2,3,4,5,6,7,8,9,0,];
function randomCapital(){
var capital=capitalAlphabets[Math.floor(Math.random()*capitalAlphabets.length)];
return capital;
}
function randomSmall(){
var small=smallAlphabets[Math.floor(Math.random()*smallAlphabets.length)];
return small;
}
function randomNumber(){
var number=numbers[Math.floor(Math.random()*numbers.length)];
return number;
}
var password="";
function makePassword(){
password="";
for(var i=0; i<=12; i++){
password=password+randomCapital()+randomSmall()+randomNumber();
// console.log(i + password);
}
console.log(password);
input=document.getElementById("password");
input.value=password;
}
//having issues with setting an even listener to prevent default in input field
You probably have your button inside a form so it is interpreted as a submit button (<button type="submit">). Pressing enter inside an input field inside a form will click on the first submit button inside the form. Just explicity make the button type a button so clicking it will not submit the form and refresh the page:
<button type="button" onclick="makePassword()">Get password</button>
If you want to add an event listener, use document.getElementById to get the DOM element to add a keypress event listener to and if the event's keycode is 13 (enter), prevent the default action.
document.getElementById("password").addEventListener("keypress", function(e){
if(e.keyCode==13){
e.preventDefault();
}
});
Overall, using onclick="" for a button is bad practice.
You should add an eventListener for your button instead:
var button = document.getElementById("button");
button.addEventListener("click", function(event) {
event.preventDefault();
makePassword();
});
That should work much better, let me know if you have any questions.
http://jsfiddle.net/316xjkqu/2/

Android Keyboard not hidden after form submit

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.

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