Detect when input focuses - javascript

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"/>

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()"/>

Disabled textbox change event

Short Explanation
I want to do something whenever disabled textbox value is changed
Detailed Explanation
I have a disabled text box which value is setting programitically I want to bind the change event of disabled textbox to fire some other function. This is what I tried but won't work.
$('#Rate').change(function() {
// alert("Change Event Called");
CalculateMedicine();
});
$('input[id$=Rate]').bind("change", function () {
CalculateMedicine();
});
This both thing don't work for me and the I don't like the idea to put a function CalculateMedicine() to all the place from which possibly Rate textbox is changing.So apart from this solution any help will be appreciated
assuming that your your input has disable class on on click or something else you check like this
if ($( "#input" ).hasClass( "disable" )) {
Your logics and codes here //
}
//Hope this would help
You can use triggerfor a change event:
<input type="text" disabled="disabled" name="fname" class="myTextBox" ><br>
<input type="button" name="submit" id="submit" value="Submit">
Javascript:
$(".myTextBox").change(function(){
console.log("yes i m working");
});
$("#submit").click("input", function() {
$(".myTextBox").val("New value").trigger("change");
});
Check Demo
It is possible if one redefines the value property of that input.
<html>
<head>
<script>
function Init(){
var tE = document.querySelector('input'); //Our input field.
//We redefine the value property for the input
tE._value = tE.value;
Object.defineProperty(tE, 'value', {
get: function(){return this._value},
set: function(v){
console.log(1, 'The value changed to ' + v)
this._value = v;
this.setAttribute('value', v) //We set the attribute for display and dom reasons
//Here we can trigger our code
}
})
}
function Test(){
//In one second we are going to change the value of the input
window.setTimeout(function(){
var tE = document.querySelector('input'); //Our input field.
tE.value = 'Changed!'
console.log(0, 'Changed the value for input to ' + tE.value)
}, 1000)
}
</script>
</head>
<body onload = 'Init(); Test();'>
<input type = 'text' disabled = 'true' value = 'Initial' />
</body>
</html>
https://jsfiddle.net/v9enoL0r/
The change event will not fire if you change the value programmatically
See https://stackoverflow.com/a/7878081/3052648
A not elegant possible solution:
function checkChanges(){
if(prevRate != $('#Rate').val()){
prevRate = $('#Rate').val();
alert('changed');
}
}
var prevRate;
$(document).ready(function(){
prevRate = $('#Rate').val();
setInterval(function(){
checkChanges();
} ,500);
});
You can fire change event by the following code from wherever you want to fire change event or any other event. The event will be fired either value changed or not. Just place the code after from where you are changing value programatically.
element.dispatchEvent(new Event('change'))
let input = document.querySelector("input");
input.addEventListener("change", () => alert("Change Event is Fired"));
input.value = "xyz";
input.dispatchEvent(new Event("change"));
<input type="text" disabled value="abc">

jquery each for all text boxes

I am using following script to bind a keypress event on each textbox so that on reaching the maxlength, focus will switch to next input field. Passing classname as the prarameters to the function.
function autoFocusPhoneFields(txtbox1ID,txtbox2ID) {
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
$(this).bind('keypress', function(){
if(this.value.length == $(this).attr('maxlength')) {
$(this).next('input').focus();
}
});
});
}
$(document).ready(function(){
autoFocusPhoneFields('mobileprefix','mobilecode');
});
As i have mentioned two different input ..it is runnign fine. Butis there any way around so that it will get the classnames and runs through each input box to attach keypress event.
If I understand you correctly, you want to attach the same event handler to every input field? Just use the selector:
$(':text')
(for all input type="text") fields.
So just change
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
to:
$(':text').each(function() {
If I get you correctly you just need to use type selector for input. You can also get rid of calling each to iterate thru inputs since binding event to multiply elements interates via them. So you can change your code into something like following:
var autoFocusPhoneFields = function () {
$('input:text').keypress(function() {
if(this.value.length == $(this).attr('maxlength'))
$(this).next('input').focus();
});
}
$(autoFocusPhoneFields);
This works fine.
HTML
<input id="one" class="inp" maxlength="5" />
<input id="two" class="inp" maxlength="3" />
<input id="three" class="inp" maxlength="2" />
JS Part
$(function(){
var onpress = function(){
var val = $(this).val();
var next_input = $(this).next('input');
var mx = $(this).attr('maxlength');
try {
mx = Number(mx);
if (next_input.length >= 1 && val.length >= mx){
next_input.focus();
}
} catch(x){}
}
$('input.inp').bind('keypress', onpress);
});

Parent element selection problem?

My HTML is something like this
<div id="mydiv" class="common">
<input type="text" id="text1" value="" />
<input type="text" id="text2" value="" />
</div>
I am assigning a function on the onclick event of the textbox like this
$(document).ready(function() {
$(".common input").click(function() {
//////// What I am trying to do is access the id of its parent
// in this case it is "mydiv"
alert($(this:parent).attr('id'));
});
But it is not working
Try $(this).parent().attr('id');
You'd be better off using event delegation and only having one event handler on the parent <div>. This will be more efficient by reducing the number of event handlers required, and by replacing the descendant and element selector with the much simpler and faster ID selector. Also, within the event handler function you automatically have references to both elements you're interested in (via evt.target and this) without having to do any traversal.
$(document).ready(function() {
$("#mydiv").click(function(evt) {
if (evt.target.tagName.toLowerCase() == "input") {
alert("Clicked input with ID " + evt.target.id);
alert("Parent ID: " + this.id);
}
});
});
Change it to the following
$(document).ready(function() {
$(".common input").click(function() {
var divId = $(this).parent().attr('id'));
alert(divId);
});
$(document).ready(function() {
$(".common input").click(function() {
alert( $(this).parent().attr('id') ); // <- Use $(this).parent()
}); // <- don't forget to close this function too
});

Using jQuery, what is the best way to set onClick event listeners for radio buttons?

For the following HTML:
<form name="myForm">
<label>One<input name="area" type="radio" value="S" /></label>
<label>Two<input name="area" type="radio" value="R" /></label>
<label>Three<input name="area" type="radio" value="O" /></label>
<label>Four<input name="area" type="radio" value="U" /></label>
</form>
Changing from the following JavaScript code:
$(function() {
var myForm = document.myForm;
var radios = myForm.area;
// Loop through radio buttons
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "S") {
radios[i].checked = true; // Selected when form displays
radioClicks(); // Execute the function, initial setup
}
radios[i].onclick = radioClicks; // Assign to run when clicked
}
});
Thanks
EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons
$(document).ready(function(){
$("input[name='area']").bind("click", radioClicks);
});
functionradioClicks() {
alert($(this).val());
}
I like to use bind() instead of directly wiring the event handler because you can pass additional data to the event hander (not shown here but the data is a third bind() argument) and because you can easily unbind it (and you can bind and unbind by group--see the jQuery docs).
http://docs.jquery.com/Events/bind#typedatafn
$( function() {
$("input:radio")
.click(radioClicks)
.filter("[value='S']")
.attr("checked", "checked");
});
$(function() {
$("form#myForm input[type='radio']").click( fn );
});
function fn()
{
//do stuff here
}
$(function() {
$('input[#type="radio"]').click(radioClicks);
});
I think something like this should work (but it's untested):
$("input[#type='radio']").each(function(i) {
if (this.val() == 'E') {
radioClicks();
this.get().checked = true;
}
}
$("input[#type='radio']").click(radioClicks);
$(function() {
$('#myForm :radio').each(function() {
if ($(this).value == 'S') {
$(this).attr("checked", true);
radioClicks();
}
$(this).click(radioClicks);
});
});

Categories