need to click 2 times to lose focus - javascript

In my form, I have some fields on which I have applied onblur event. Problem is if I click on save directly after entering some field, save does not get called. I need to click twice.
For more clarifications, refer to steps below and code snippet is also attached.
1) Enter some value in input box
2) Lose focus by either tabing out or clicking somewhere else on screen
3) it works fine and function triggerOnBlur gets invoked
4) now enter some value in input box again
5) straight away click on save button, without clicking anywhere else
6) function triggerOnBlur gets invoked, but in order to click save button, I need to click on save.
I want to get it done in one click..
<!DOCTYPE html>
<html>
<head>
<script>
function triggerOnBlur()
{
alert("onblur event triggered");
}
function triggerSaveButton()
{
alert("save button");
}
</script>
</head>
<body>
<form>
<input type = "text" onblur = "triggerOnBlur()" />
<input type = "submit" value = "Save" onclick = "triggerSaveButton()" />
</form>
</body>
</html>

You could always do something like:
function triggerSaveButton()
{
var inputs = document.getElementsByTagName("input"), input = null;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(input.type == "text" && input == document.activeElement) {
input.blur();
}
}
// onblur triggered, now continue with function
alert("save button");
}

Because your alert() break the click event, click event need you release mouse key on the button, if you must use alert(), you may use onmousedown event, look at this example
http://jsfiddle.net/3w8VM/

Related

Get the keyboard button pressed during onClick and based on that run different functions

Currently, I have 9 different functions which has to triggered by single button when onclick and keyboard numpad (1 to 9).
Edit: Solution by Sode- v2
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button type="button" id="b41" onclick="test_ks(event)">Shape Anchor Point</button>
<script>
const pressedButtons = {};
window.onkeydown = (e) => (pressedButtons[e.which] = true);
window.onkeyup = (e) => (pressedButtons[e.which] = false);
function test_ks(event) {
if (pressedButtons[97]) {
alert('numpad 1');
} else if (pressedButtons[98]) {
alert('numpad 2');
}
}
</script>
</body>
</html>
Tried this at
https://manjunath7472.w3spaces.com/saved-from-Tryit-2021-11-06.html
Issue
1.After clicking numberpad 1, numberpad 2 doesn't work & After clicking numpad2, numpad1 works but after that numpad 2 doesn't work.
2.After initial click on anyone, from second time, with just mouse
click(without pressing keyboard numpad) it triggers the alert.
3.After first clcik with keypress, it doesn't consider keyboard press and alert is triggered by mouse click only.
When you bind a function to onclick in the HTML tag you want to just pass the name of the function as the event parameter will be passed in by the DOM
<button type="button" id="b41" onclick="myFunction()">myButtonName</button>
but also, a button's click event won't have any keyboard data attached to it, so you may want to look into using keydown and keyup event listeners (probably on the window object) to keep track of which keys are pressed and using that information when the button is clicked
<button type="button" id="b41" onclick="myFunction()">myButtonName</button>
<span id="output"></span>
<script>
const pressedButtons = {};
const outputSpan = document.querySelector('#output');
window.onkeydown = (e) => (pressedButtons[e.which] = true);
window.onkeyup = (e) => (pressedButtons[e.which] = false);
function myFunction(event) {
console.log(pressedButtons);
if (pressedButtons[97]) {
outputSpan.innerHTML = 'numpad 1';
} else if (pressedButtons[98]) {
outputSpan.innerHTML = 'numpad 2';
} else {
outputSpan.innerHTML = '';
}
}
</script>
Edit: updated to change text of a span rather than use alert()

Radio input checked with keyboard shortcut doesn't trigger event change

I have added a keyboard shortcut to my script so that when I press ctrl + 1 the first "source" radio input is checked :
if (e.key == "1" && e.ctrlKey) {
document.getElementsByName("source")[0].checked = true;
}
So far everythin is good. I have added an event listener so that when the state of my radio input are changed, then several things happen. But this event listener isn't triggered when I press ctrl+1 even thought the state of the radio input is changed (I can see the color of the input changing). If click manually on the radio input then the event listener is working:
var radiosource = document.getElementsByName("source");
for (var i = 0; i < radiosource.length; i++) {
radiosource[i].addEventListener('change', function (e) {
var input_changed_id = e.target.id;
if (input_changed_id.includes("en")) {
document.getElementById("fr_target").checked = true;
current_target = "fr";
}
if (input_changed_id.includes("fr")) {
document.getElementById("en_target").checked = true;
current_target = "en";
}
translate();
});
}
Here is the full script (cf lines 119 and lines 49 and 322)
It won't trigger if you change the checked value manually but your event will trigger if you simulate the click on the radio button using .click().
So just update your keyboard shortcut script to this:
if (e.key == "1" && e.ctrlKey) {
document.getElementsByName("source")[0].click();
}

Function activate after two onclicks

Hey I'm using javascript+html only.
Is there any way to activate a function after the button has been clicked two (or more) times? I want the button to do NOTHING at the first click.
For a "doubleclick", when the user quickly presses the mouse button twice (such as opening a program on the desktop), you can use the event listener dblclick in place of the click event.
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/dblclick
For a quick example, have a look at the below code. http://jsfiddle.net/jzQa9/
This code just creates an event listener for the HTMLElement of "item", which is found by using getElementById.
<div id="item" style="width:15px;height:15px;background-color:black;"></div>
<script>
var item = document.getElementById('item');
item.addEventListener('dblclick',function(e) {
var target = e.target || e.srcElement;
target.style.backgroundColor = 'red';
},false);
</script>
As for wanting the user to click an element X times for it to finally perform an action, you can do the following. http://jsfiddle.net/5xbPG/
This below code works by adding a click tracker to the HTMLElement and incrementing the click count every time it's clicked. I opted to save the clicks to the HTMLElement instead of a variable, but either way is fine.
<div id="item" style="width:15px;height:15px;background-color:black;"></div>
<script>
var item = document.getElementById('item');
item.addEventListener('click',function(e) {
var target = e.target || e.srcElement;
var clicks = 0;
if(target.clicks)
clicks = target.clicks;
else
target.clicks = 0;
if(clicks >= 4) {
target.style.backgroundColor = 'red';
}
target.clicks += 1;
},false);
</script>
== UPDATE ==
Since you recently posted a comment that you want two different buttons to be clicked for an action to happen, you would want to do something like this... http://jsfiddle.net/9GJez/
The way this code works is by setting two variables (or more) to track if an element has been clicked. We change these variables when that item has been clicked. For each event listener at the end of changing the boolean values of the click state, we run the function checkClick which will make sure all buttons were clicked. If they were clicked, we then run our code. This code could be cleaned up and made to be more portable and expandable, but this should hopefully get you started.
<input type="button" id="button1">
<input type="button" id="button2">
<div id="result" style="width:15px;height:15px;background-color:black;"></div>
<script>
var result = document.getElementById('result');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button1Clicked = false;
var button2Clicked = false;
button1.addEventListener('click',function(e) {
button1Clicked = true;
checkClick();
},false);
button2.addEventListener('click',function(e) {
button2Clicked = true;
checkClick();
},false);
function checkClick() {
if(button1Clicked && button2Clicked) {
result.style.backgroundColor = 'red';
}
}
</script>
Two ways you can do this, one would be to have a data attribute within the html button that identifies whether the click has been done.
<button id="btn">Click Me!</button>
<script>
var clickedAlready = false;
document.getElementById('btn').onclick = function() {
if (clickedAlready) {
//do something...
}
else
clickedAlready = true;
}
</script>
While global variables aren't the best way to handle it, this gives you an idea. Another option would be to store the value in a hidden input, and modify that value to identify if it's the first click or not.
Maybe something like this?
var numberTimesClicked = 0;
function clickHandler() {
if (numberTimesClicked > 0) {
// do something...
}
numberTimesClicked++;
}
document.getElementById("myBtn").addEventListener("click", clickHandler);

press a button without id or name with javascript

i need to press a button in one page, but the button dont have id, name or anything else
only this is the code of the button:
<input type="submit" value="continue">
there is a way to press it?
i tried this code from here:
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'button' && buttons[i].value == val)
{
buttons[i].click();
break; //this will exit for loop, but if you want to click every button with the value button then comment this line
}
}
}
but dont worked too, nothing happen, the page refresh but still in the same place
Your input is type "submit", however your javascript is looking for type "button". Try changing to this:
function clickButton(val)
{
var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++)
{
if(buttons[i].type == 'submit' && buttons[i].value == val)
{
buttons[i].click();
break; //this will exit for loop, but if you want to click every button with the value button then comment this line
}
}
}
And ensure that you pass the correct value when calling this function:
clickButton('continue');
Type of your button is "submit" not "button":
<input type="submit" value="continue">
Change this:
buttons[i].type == 'submit'

How do I convert Enter to Tab (with focus change) in IE9? It worked in IE8

I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.
<input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
name="" value="" />
<!-- Other inputs exist as created via the DOM, but they are not sibling elements. -->
Javascript:
function enterToTab(myEvent) {
if (myEvent.keyCode == 13) {
myEvent.keyCode = 9;
}
}
function changeEvent(myInput) { var test = "hello"; }
In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)
Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?
Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.
Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.
UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?
Looks like IE9 events are immutable. Once they've been fired you can't change the properties on them, just preventDefault() or cancel them. So you best option is to cancel any "enter" events and re-dispatch a new DOM event from the text input.
Example
function enterToTab(event){
if(event.keyCode == 13){
var keyEvent = document.createEvent("Event");
// This is a lovely method signature
keyEvent.initKeyboardEvent("onkeydown", true, true, window, 9, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(keyEvent);
// you may want to prevent default here
}
}
Here's the MSDN documentation around IE9 DOM events:
Event Object - http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx
createEvent - http://msdn.microsoft.com/en-us/library/ff975304(v=vs.85).aspx
initialize a Keyboard Event - http://msdn.microsoft.com/en-us/library/ff975297(v=vs.85).aspx
Here is a different idea; change the on submit so that it calls a function instead of processing the form. in the function check all the fields to see if they are blank, then focus on the next field that doesn't have a value.
So they type a value into field 1, hit enter, and the function runs. it sees that field 1 is full, but field 2 isn't, so focus on field 2.
Then when all the fields are full, submit the form for processing.
If the form has fields that can be blank, you could use a boolean array that would keep track of which fields received focus using the onfocus() event.
Just an outside the box idea.
The previous IE-version allowed the non standard writable event.keyCode property, IE9 now conforms to the standards.
You may want to consider the functionality you are after: you want to make the enter key behave like the tab key, i.e. moving the focus to the next (text) input field. There are more ways to do that. One of them is using the tabindex attribute of the text input fields. If you order the fields in your form using this tabindex attribute, the functions I present here may yield the same result as your previous keyCode method. Here are two functions I tested in this jsfiddle. An (text) input field now looks like:
<input type="text"
onkeypress="nextOnEnter(this,event);"
name="" value=""
tabindex="1"/>
the functions to use for tabbing:
function nextOnEnter(obj,e){
e = e || event;
// we are storing all input fields with tabindex attribute in
// a 'static' field of this function using the external function
// getTabbableFields
nextOnEnter.fields = nextOnEnter.fields || getTabbableFields();
if (e.keyCode === 13) {
// first, prevent default behavior for enter key (submit)
if (e.preventDefault){
e.preventDefault();
} else if (e.stopPropagation){
e.stopPropagation();
} else {
e.returnValue = false;
}
// determine current tabindex
var tabi = parseInt(obj.getAttribute('tabindex'),10);
// focus to next tabindex in line
if ( tabi+1 < nextOnEnter.fields.length ){
nextOnEnter.fields[tabi+1].focus();
}
}
}
// returns an array containing all input text/submit fields with a
// tabindex attribute, in the order of the tabindex values
function getTabbableFields(){
var ret = [],
inpts = document.getElementsByTagName('input'),
i = inpts.length;
while (i--){
var tabi = parseInt(inpts[i].getAttribute('tabindex'),10),
txtType = inpts[i].getAttribute('type');
// [txtType] could be used to filter out input fields that you
// don't want to be 'tabbable'
ret[tabi] = inpts[i];
}
return ret;
}
If you don't want to use tabindex and all your input fields are 'tabbable', see this jsfiddle
[EDIT] edited functions (see jsfiddles) to make use of event delegation and make it all work in Opera too. And this version imitates shift-TAB too.
The code above causes problems. Here's some code that will help you. Works on IE9, FF5 etc.
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
And then you should just create your input texts or whatever
<input type="text" id="1" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="2" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="3" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="4" onkeydown="return tabOnEnter(this,event)"/>
A <button> element on a page will cause this problem.
In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.
<button type="button">Click me!</button>
Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.
Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE problem with Enter key and <button> elements</title>
</head>
<body>
<script>
function press(event) {
if (event.keyCode == 13) {
document.getElementById('input2').focus();
// In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
// event.preventDefault && event.preventDefault();
}
}
</script>
<input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
<input id="input2" type="text" value="input2. Press enter here." /><br />
<input id="button1" type="button" value='I am an <input type="button">' /><br />
<button id="button2" type="button">I am a <button type="button"></button><br />
<button id="button3">I am a <button>. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>
Mike Fdz's code is superb. In order to skip over hidden fields, you may want to change the line
return form.elements[++e % form.elements.length];
to this:
e++;
while (form.elements[e % form.elements.length].type == "hidden") {
e++;
}
return form.elements[e % form.elements.length];
Use onpaste along with onkeypress like
Consider you have wrriten a javascript function which checks the text lenght so we will need to validate it on key press like as below
<asp:TextBox ID="txtInputText" runat="server" Text="Please enter some text" onpaste="return textboxMultilineMaxNumber(this,1000);" onkeypress="return textboxMultilineMaxNumber(this,1000);"></asp:TextBox>
onkeypress will work in both FF and IE
but if you try to do ctr+V in textbox then onpaste will handle in IE in FF onkeypress takes care of it
This is what I have done with what I found over the internet :
function stopRKey(evt)
{
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio")))
{
getNextElement(node).focus();
return false;
}
}
function getNextElement(field)
{
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
e++;
while (form.elements[e % form.elements.length].type == "hidden")
{
e++;
}
return form.elements[e % form.elements.length];;
}
To prevent a "submit event" triggered by Enter-Keyboard in your Form in IE9, retire any button inside the form area. Place him (button) in outside of form's area.
function enterAsTab() {
var keyPressed = event.keyCode; // get the Key that is pressed
if (keyPressed == 13)
{
//case the KeyPressed is the [Enter]
var inputs = $('input'); // storage a array of Inputs
var a = inputs.index(document.activeElement);
//get the Index of Active Element Input inside the Inputs(array)
if (inputs[a + 1] !== null)
{
// case the next index of array is not null
var nextBox = inputs[a + 1];
nextBox.focus(); // Focus the next input element. Make him an Active Element
event.preventDefault();
}
return false;
}
else {return keyPressed;}
}
<HTML>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onKeyPress="return enterAsTab();">
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
</body>
</HTML>

Categories

Resources