How can I make focus event happened on the dynamically inserted input? - javascript

$("input").focus(function(){
console.log('input focused');
});
Above is my code to test if focus event happened.And I made a button to insert another input dynamically.But while I focus the inserted inputs,no console logged at all.
Can anybody help?
Thanks

You need to use event delegation with the focusin event as focus does not support bubbling(event delegation requires bubbling support to work).
$("input").focus(function() {
snippet.log('input focus: ' + $('input').index(this));
});
$('#dynamicarea').on('focusin', 'input', function() {
snippet.log('input focusin: ' + $('input').index(this));
});
$('button').click(function() {
$('div').append('<input />');
})
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
<input />
<input />
<br />
<button>Add</button>
<div id="dynamicarea"></div>

function focused(evt){
var target = evt.target;
var target_name = evt.target.nodeName;
$(target).keydown(function(e){
if(e.which==9 && $(e.target).parent().parent().is(":last-of-type")){
e.preventDefault();
}else{
$(this).unbind("keydown");
}
});
}
<sectionA>
<input>
/*insert input here*/
</sectionA>
<sectionB>
<input>
<input>
</sectionB>
Originally I was trying to stop focusing to the next input in the sectionB which is not in the viewport when pressing the tab. So I write a function above to bind in the inserted input to tell. But Arun's answer also work. Thanks a lot.

Related

Chrome and Edge treating a checkbox set to "indeterminate" differently when checked

Note: I'm using jQuery to access the DOM element but plain JavaScript to assign the event to it, so I doubt jQuery has anything to do with it
Check this jsFiddle.
$(document).ready(function() {
$('input')[0].indeterminate = true;
$('input')[0].addEventListener("click", function(event) {
console.log(event.target.checked)
alert("Check is: " + event.target.checked);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked>
If you open it on Chrome and click on the checkbox, the alert message says "Check is: false" whereas if you open it on Microsoft Edge and click on the checkbox, the message says "Check is: true", meaning that the state of the check property changes with the browser.
I tried setting the checked property along with the indeterminate property to see if I enforced that it would treat it the same way, but the results are the same
$(document).ready(function() {
$('input')[0].indeterminate = true;
$('input')[0].checked = false;
$('input')[0].addEventListener("click", function(event) {
console.log(event.target.checked)
alert("Check is: " + event.target.checked);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked>
Is this a bug on Edge or Chrome or is there a way to have a congruent behavior across all browsers?
This behavior is related to the indeterminate property. Please refer to Racil Hilan 's reply on this thread.
Checkbox inputs can only have two states: checked or unchecked. The indeterminate state is visual only and it masks the real state of the checkbox.
The first time you click on a checkbox that has its indeterminate set to "true" will simply change it to false and the checkbox will show its real state. For that reason, the change from "indeterminate" to either "checked" or "unchecked" is not a change in the real state and it does not trigger the "onchange" event.
Although IE implementation is the correct one technically, the implementation of the other browsers is the more practical one. For most applications, the visual "indeterminate" state needs to be considered as a real state just like the "checked" and "unchecked" which means that the change from any of those 3 states to another one should trigger the onchange event.
You could add a change event to verify it. In IE and Edge, the first time you click on a checkbox, it will not trigger the change event, just reveal the real state of the checkbox. But, in Chrome, it will trigger the change event and change the real state to the other real state.
code as below:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('input')[0].indeterminate = true;
//$('input')[0].checked = false;
$('input')[0].addEventListener("click", function (event) {
console.log(event.target.checked)
alert("Check is: " + event.target.checked);
});
$('input')[0].addEventListener("change", function (event) {
console.log(event.target.checked)
alert("change event Check is: " + event.target.checked);
})
});
</script>
<input type="checkbox" checked>
</body>
Is this a bug on Edge or Chrome or is there a way to have a congruent
behavior across all browsers?
If you want to have a congruent behavior across all browsers, you could try to set the indeterminate to false or remove this property.
Also, you could refer to the following code to use one-time click event:
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var checkbox = document.getElementById("cb");
checkbox.indeterminate = true;
$('#cb').one('click', function (e) {
if (!this.checked) {
this.checked = true;
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
this.dispatchEvent(evt);
}
alert(e.target.checked);
}).change(function (e) {
console.log(e);
alert(e.target.checked)
});
});
</script>
</head>
<body>
<label for="cb">
<input id="cb" type="checkbox" checked />click me
</label>
</body>

Change function on Javascript/jQuery

I have a textfield, and I want the field to be disabled or read only if I change text on the field. But, before that, I can't make change function. I don't know why.
I have tried this code :
$("#submitOrder_cust_id_name").click(function () {
alert("Test");
});
and when I click the field it is working.
But, when I use this code
$("#submitOrder_cust_id_name").change(function () {alert("Test");});
or this code
$("#submitOrder_cust_id_name").on('change', function () {
alert("Test");
})
it doesn't work at all.
Please help. Thanks.
jquery change event trigger only when hit enter on the text box. If you want to trigger a event when you enter any character use "keypress" instead of "change"
Refer this :
https://www.w3schools.com/jquery/event_keypress.asp
use on 'change':
$('#submitOrder_cust_id_name').on('change', function () {
alert('test');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="submitOrder_cust_id_name" />
Try using .blur(). This will be called when the input field loses focus:
$('#submitOrder_cust_id_name').on('blur', function () {
alert('test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="submitOrder_cust_id_name" />

digitalbush input mask position of cursor jquery

DEMO
jQuery(function($){
$("#date").mask("99/99/9999",{placeholder:"mm/dd/yyyy"});
$("#phone").mask("(999) 999-9999");
$("#tin").mask("99-9999999");
$("#ssn").mask("999-99-9999");
});
I have tried using the digitalbush input mask. It is working ok.
The problem is , I wanted to make the cursor appear to the left most part of the input when the input is focused.I cant find a way to do this.Also i wanted to call the .change(); event of the input by doing something like this
jQuery(function($){
$("#phone").mask("(999) 999-9999");
$("#phone").change();
});
Unfortunately the event is not called.
How to place the cursor to left most part of input on focus.
Call event .change() of input after finish typing.
I tried making a demo but i cant make the maskedinput work. Please bear with it.
$(document).ready(function() {
$("#id").focus(function() {
jQuery(function($) {
$.mask.definitions["9"] = null;
$.mask.definitions["^"] = "[0-9]";
$.mask.definitions["N"] = "[N,V]";
$("#id").mask("^^^-^^^-^^^-^^^N");
$("#id").change();
});
});
$("#id").change(function() {
console.log('change')
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/digitalBush/jquery.maskedinput/1.4.1/dist/jquery.maskedinput.js"></script>
<input type="text" id="id" name="" maxlength="20" class=" ">

Blur event cancels Click events with jQuery on Mobile device

I have a blur event in a textarea:
$("#question-id-5-answer").blur(function (event) {}
And a click event in the Submit button:
$("#" + _sendBtnId).on("click", function () {}
It happens that the Click event does not fire because the Blur event cancel the click event.
I can't use the Mousedown event because it's a touch device that does not detect it.
I tried saving the following on my mobile device as a htm file and accessed using Forefox application. Appears to be working as expected. Please have a look if it helps you.
<form id="myForm">
<textarea id="myTxt"></textarea>
<input type="button" id="butSubmit" value="Submit" />
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#myTxt").blur(function() {
if($(this).val() != "") {
alert("retunging false");
return false;
}
alert("rextarea is empty");
});
$("#butSubmit").click(function() {
alert("submitted");
});
});
</script>

Jquery Keyboard Event trigger

I am trying to simulate a Keyboard event with jquery. What I want is when I click a button, I want a character to appear in a textarea. I need the action to be a keyboard simulation not a simple append. I have tried all the possible solutions on the web without any success, so I would be grateful if anyone can help me.
Here is my HTML/JS/Jquery code :
<html>
<head></head>
<body>
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<input type='text' id="input"></input>
<script type='text/javascript'>
function simulateKeyPress() {
document.getElementById("text").focus();
var e = $.Event("keypress");
e.which = 97;
$("input").trigger(e);
}
</script>
<br/>
<button id="button" onclick='simulateKeyPress()'>Press Me</button>
</body>
</html>
As you can see, when the button is clicked, I only get a focus on the text element, but no character appears, any ideas?
looks like I was not clear enough. Here is another sample, I am using the MouseTrap library to capture keyboard events.
Here is my code.
<html>
<header>
<title>test</title>
</header>
<script type='text/javascript' src='MouseTrap.js'></script>
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<body>
<input type='text' class="mousetrap" id="input"></input>
<script type='text/javascript'>
Mousetrap.bind('4', function(){alert("you pressed 4" );});
function simulateKeyPress(character) {
document.getElementById("input").focus();
var input = $('#input');
input.val(input.val() + character);
}
</script>
<br/>
<button type="button" onclick='simulateKeyPress(4)'>Press Me</button>
</body>
</html>
With this code, whenever you press '4' on the keyboard, an alert box will appear. All I want is when I click the button, the same event to be created. Ideas?
Here is one solution to simulate the keypress :
var input = $('#input');
$('#button').click(function(){
// Add a character to the input
input.val(input.val() + 'x');
// Trigger the keypress event
input.keypress();
});
// Check if it work
input.on('keypress', function(){
alert('key pressed!');
});
Here is a jsfiddle demo.
Javascript does not perform default actions when you fire it from javascript. So the only way is to create your own vent handler :
function simulateKeyPress() {
document.getElementById("text").focus();
var e = $.Event("keypress");
e.which = 97;
$("input").trigger(e);
}
$("input").on('keypress', function(e){
//append e.which to your input here
});
It doesn't seem possible to acheieve this without appending the characters manually to the textarea.
The answers that #HighKickX and #claustrofob wrote only triggers the event handler as if the specificed key was pressed, but not actually presses that key like happens when a key is pressed on the keyboard (probably due to security reasons).
Because only the event is fired but the key is not actually pressed the textarea won't have that character added automatically.
try this
<input id="field">
<button id="x" class="button">submit</button>
$(".button").click(function() {
var value = $("#field").val();
$("#field").val( $("#field").val() + value);
});

Categories