Avoid $(document).click for certain textfiels - javascript

I've got 2 text fields and a button and also a $(document).click function to trigger showItems() function.
My question is how can I avoid showItems() from been triggered if the user is currently typing anything into those 2 text fields?
<input type="text" id="tf1">
<input type="text" id="tf2">
<button id="bt1">Preference</button>
$(document).click(function(){
if (typeof showItems() == "function") {
showItems();
}
});

You can check whether the click passed through #tf1 or #tf2:
$(document).click(function(e) {
if ($(e.target).closest("#tf1, #tf2").length) {
return;
}
if (typeof showItems == "function") {
showItems();
}
});
Example:
$(document).click(function(e) {
if ($(e.target).closest("#tf1, #tf2").length) {
return;
}
$("<p>click</p>").appendTo(document.body);
});
<input type="text" id="tf1">
<input type="text" id="tf2">
<button id="bt1">Preference</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Also note that when checking the type of showItems, you don't want the () on it, that will call it and check the type of what it returns. I've removed the () in the first code block above.

The simplest solution would be this:
<input type="text" id="tf1" onclick="event.stopPropagation()">
The click events bubble up the DOM from the element that was clicked. This way you stop it from bubbling up and it never reaches the document root.

event.stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
$(document).click(function() {
if (typeof showItems == "function") {
showItems();
}
});
function showItems() {
console.log('Here!');
}
$('#tf1,#tf2').on('click', function(e) {
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="tf1">
<input type="text" id="tf2">
<button id="bt1">Preference</button>
Fiddle here

using .click() function without a target is never a good idea. rather use the button as a target for your click event for example:
<input type="text" id="tf1">
<input type="text" id="tf2">
<button id="bt1">Preference</button>
$("#bt1").click(function(){
if (typeof showItems() == "function") {
showItems();
}
});
but i am not sure when you want your click-event to actually fire.

Related

How to trigger a function when the typing cursor leaves the input text field?

I want to trigger a function when the typing cursor leaves the input text field. Does such an event exists? If someone knows please let me know, Thanks.
// to trigger this function
function trigger () {
console.log("no longer able to type in input text);
}
Just use onblur. You can do this in both vanilla js and jquery.
Vanilla Js:
function test() {
alert('Exited');
}
document.getElementById('waffle').addEventListener('blur', function(){
alert('exited waffle');
});
<input type="text" onblur="test()">
<input type="text" id="waffle">
With JQuery:
$('#test').on('blur', function(){
alert('exited');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" type="text">
Jquery Ref: https://api.jquery.com/blur/
Vanilla: https://developer.mozilla.org/en-US/docs/Web/Events/blur
Yes, there is an event that you can bind a function to called "blur". It looks like this if you use addEventListener():
document.getElementById("myInput").addEventListener("blur", function() {
alert("focused out");
});
<input id="myInput"/>
Or if you have a named function, myFunction, you can register it on the DOM element via the input tag:
function myFunction() {
alert("focused out");
};
<input onblur="myFunction()"/>

Detect when input focuses

Sorry if this has already been asked, but all the results I've found use jQuery.
I have the following code:
<script>
var nameBox = document.getElementById('name');
if(nameBox == document.activeElement) {
console.log('name element focused')
}
</script>
But, nothing gets logged to the console when I click on the input. What am I doing wrong? (I would like to do this without jQuery)
In your case you are detecting if the element is active during the script's run, so you get false. After it you don't have any detectors. So you need to use addEventListener() function and add handler for focus event. It will fire when element is focused.
document.getElementById('inp').addEventListener('focus', function(){
console.log('Focused');
});
<input id="inp" />
You are testing if the element is focused now instead setting up an event listener to do something when it gains the focus.
function your_function(event) {
console.log('name element focused')
}
nameBox.addEventListener("focus", your_function);
There are some ways you can do this:
1. onFocus:
function focused(element) {
element.style.background = "gold";
}
<input type="text" onfocus="focused(this)">
<input type="text" onfocus="focused(this)">
2. addEventListener
inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('focus', function(element){
document.activeElement.style.background="gold"
});
}
<input type="text"/>
<input type="text"/>
3. Jquery focus:
$(function(){
$( "input" ).focus(function(e) {
$(this).css( "background", "gold" );
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>
<input type="text"/>

Textbox change event not effecting immediately jquery

I am trying to enable img button in while typing in textbox. But it is working after lost focusing from textbox. How can see changes immediately?
$("[id$='txtNewPass2']").change(function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
Use the keyup input event.
$("[id$='txtNewPass2']").on('input', function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
The reason for recommending a keyup as opposed to a keydown is that in the below snippet, if you use a keydown the event will always be one letter behind.
Update:
After playing around with the example I created below. I can see that the input event creates a much smoother update effect. See the example below to see how all three work comparitively
Sample:
$('#keyup-input').on('keyup', function () {
$('#keyup-div').html($('#keyup-input').val());
});
$('#keydown-input').on('keydown', function () {
$('#keydown-div').html($('#keydown-input').val());
});
$('#input-input').on('input', function () {
$('#input-div').html($('#input-input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Keyup:</h1>
<input id="keyup-input" type="text" />
<div id="keyup-div"></div>
<br/>
<br/>
<h1>Keydown:</h1>
<input id="keydown-input" type="text" />
<div id="keydown-div"></div>
<br/>
<br/>
<h1>Input:</h1>
<input id="input-input" type="text" />
<div id="input-div"></div>
#James123 I hope it will work as you want.I just used Input event instead of change
$("[id$='txtNewPass2']").on("input",function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});

jQuery UI Dialog Button Won't Click

The alert is working, but the button just won't click...
$('#loginDialog .field input').keyup(function (e) {
if (e.keyCode == 13) {
alert('it is working!');
$('.ui-button').click();
return false;
}
});
I have tried many different things, including reinitializing the method when the dialog gets opened, but nothing seems to work...
Html:
<div id="loginDialog" title="Please Login">
<div class="label">Password:</div>
<div class="field"><input type="password" /></div>
</div>
the ui-button is generated by jquery ui
I'm assuming from your comment that the button is generated dynamically and that any click event you have bound to is will have to be bound using event delegation, similar to:
$('body').on('click', '.ui-button', function(){...)
Instead of body, using the closest static element will work as well and would be preferred.
Please, try this:
$(function() {
$('#loginDialog .field input').keyup(function (e) {
if (e.keyCode == 13) {
alert('it is working!');
$('.ui-button').trigger('click');
return false;
}
});
$('.ui-button').click(function() {
alert('hello world');
});
};
Here there is an example: http://jsfiddle.net/netme/YZH3B/
This should trigger the event ...
$('.ui-button').trigger('click');

focus() does not seem to work after onblur()

I have a list of input fields and when I tab through them I want to loop back to the first one, but it doesn't seem to work.
Here is my HTML
<form id="form">
<input id="mon" type="text"/> Month<br>
<input id="day" type="text"/> Day<br>
<input id="num" type="text"/> Year<br>
<input id="amt" type="text"/> Amount<br>
</form>
and my javascript
window.onload=function(){
$('mon').focus();
$('amt').onblur=function(){
//Process the input fields
$('mon').focus();
}
}
function $(a){return document.getElementById(a)}
I think your onblur event handler is being called before the default handler, causing focus to shift first to input 'mon', then to whatever the browser thinks should be in focus next. Try using the onkeypress event. e.g.
window.onload=function(){
$('mon').focus();
$('amt').onkeydown = function(e) {
//check for IE weirdness
if (e === undefined && event !== undefined)
e = event;
if (e.keyCode == 9) {
$('mon').focus();
return false;
}
}
}
function $(a){return document.getElementById(a)}
Edit: onkeydown actually seems to work in more browsers
Edit 2: added IE case. IE doesn't always pass the event as an argument
For the cursor to appear on the first input box, you need to assign the value of the input box to itself (hack). Also you need to "return false" to stop the event propagation. The modified blur function is below,
<input id="mon" type="text" onfocus="this.value=this.value;" />
$('amt').onblur = function(){ $('mon').focus(); return false; }
Take a look at this fiddle. I think this is what you want to achieve.
http://jsfiddle.net/CucuIonel/7Fpu3/7/

Categories