JQuery - focus triggers keyup event in target input - javascript

I will demonstrate my problem using the simple example. Consider the following script
$(document).on('keydown','#input1', function(e)
{
if(e.keyCode==13){ $("#input2").focus(); }
});
and HTML
<input type="text" id="input1"/>
<input type="text" id="input2" onkeyup='alert("UP")'/>
every time I press enter in the first input, focus goes to the second input but keyup event is triggered also. I tried stopPropagation but it does not work. How can I prevent that issue?

I'd say you could use keyup instead of keydown
$(document).on('keyup','#input1', function(e)
{
if(e.keyCode==13){ $("#input2").focus(); }
});
jsFiddle Demo

Related

How to simulate complete user input with events

I need to simulate a user input in an input field:
<input type="text" id="name">
The following events should get triggered manually:
mousedown > focus > mouseup > click > keydown > keypress > change >
blur
Code show here
If I use this code, they should get detected:
var element = document.getElementById('name');
$(element).on('mousedown focus mouseup click keydown keypress change blur', function(e){
console.log(e);
});
Updated file (doesn't get detected, no console logs..):
$("#name").trigger("mousedown");
$("#name").trigger("focus");
$("#name").trigger("mouseup");
$("#name").trigger("click");
$("#name").trigger("keydown");
$("#name").trigger("keypress");
$("#name").trigger("change");
$("#name").trigger("blur");
var element = document.getElementById('name');
$(element).on('mousedown focus mouseup click keydown keypress change blur', function(e){
console.log(e);
});
You would use jQuery's trigger for this. So, if you wanted to simulate the events in the order you described:
$("#name").trigger("mousedown");
$("#name").trigger("focus");
$("#name").trigger("mouseup");
$("#name").trigger("click");
$("#name").trigger("keydown");
$("#name").trigger("keypress");
$("#name").trigger("change");
$("#name").trigger("blur");
If you want to really similuate a user, you could use some setTimeout to simulate human delay as well. Good luck!
Try This --
Add Jquery plugin
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" id="name">
//var element = document.getElementById('name');
$("input").trigger("mousedown");
$("input").trigger("focus");
$("input").trigger("mouseup");
$("input").trigger("click");
$("input").trigger("keydown");
$("input").trigger("keypress");
$("input").trigger("change");
$("input").trigger("blur");
You can use the trigger jquery function to simulate and trigger any events.

Cancel Backspace and all key press when inside a textbox

I have following sample code at https://js.do/sun21170/254818
My goal is to prevent editing of text inside the textbox without using the readOnly or disabled attribute. In above demo code, I am canceling the keyup event when Backspace is pressed, but this is having no effect.
Question: Is it possible to cancel the Backspace key press using JavaScript or jquery when inside a text box without using readOnly or disabled attribute of textbox?
The code of my demo is also as pasted below.
function keyPressed(e) {
e.preventDefault();
}
function keyUp(e) {
e.preventDefault();
}
#text1 {
width:500px;
}
<input type="text" id="text1" onkeypress="keyPressed(event)"
onkeyup="keyUp(event)" value="This is some text that should not be editable"></input>
I change onkeypress="keyPressed(event)" to onkeydown="keyPressed(event)", it works.
You could use the below code snippet:
$(document).keydown(function (e) {
var element = e.target.nodeName.toLowerCase();
if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly") || (e.target.getAttribute("type") ==="checkbox")) {
if (e.keyCode === 8) {
return false;
}
}
});
Certain things to keep in mind when implementing such a functionality, you should also be checking for readyOnly textBoxes or textAreas since a backspace in such an area will result in you leaving the page (assuming you want to prevent a backspace as well).
EDIT: The code is in jQuery.
Change your onkeypress event to onkeydown and your code will work with backspace and delete button as well. The onkeyup event is not necessary
<input type="text" id="text1" onkeydown="keyPressed(event)" value="This is some text that should not be editable"></input>
I think you have to trigger the keydown event. But this is a working example. Just give every input you don't want to change the class notEditable and the jquery code will prevent the input field to be edited.
$('.notEditable').on('change keydown', function(e){
e.preventDefault();
});
#text1 {
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text1" class="notEditable" value="This is some text that should not be editable"></input>
This code is a little bit cleaner since you only have to add the class and don't need the functions to be called in the html code. However, if you would like to keep the function call in your code, simply change the your input field to this:
<input type="text" id="text1" onkeypress="keyPressed(event)" onkeydown="keyUp(event)" value="This is some text that should not be editable"></input>

onClick vs onFocus on input element

To move focus on the end of inputs when user click the input box,
I use something like this,
$(function() {
$('#test-input').on('click', function(evt) {
$target = $(evt.target);
var val = $target.val();
$target.val('').val(val);
});
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test" id="test-input" value="abcdefgh" />
But if I change the 'click' to 'focus', it doesn't work.
$(function() {
$('#test-input').on('focus', function(evt) {
$target = $(evt.target);
var val = $target.val();
$target.val('').val(val);
});
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test" id="test-input" value="abcdefgh" />
How different onClick and onFocus actions in that case?
There's some differences:
onClick: This event is fired whenever the user clicks in an object, like a button, an image, an input... After the click, then comes the:
onFocus: This event is fired when an element is selected, it doesn't need to be clicked, it can be done programmatically, calling .focus() or using the Tab key, for example. Also, using onfocus instead of onclick, can help to avoid bubbling.
To finish, use the snippet below (I added more inputs, cycle through it with TAB (or click too), you'll see the caret going to end on all of then.
Why I added a timeout?
Chrome Browser has an odd quirk where the focus event fires before the cursor is moved into the field, so, the event must wait to the cursor to get there before moving it to the end.;
$(function() {
$('.test-input').on('focus', function(evt) {
that = this;
setTimeout(function() {
that.selectionStart = that.selectionEnd = 10000;
}, 1);
});
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test" class="test-input" value="abcdefgh" />
<input type="text" name="test" class="test-input" value="a1b2c3" />
<input type="text" name="test" class="test-input" value="abcdefghijklmnop" />
Extra:
If you are programming just for mobiles, will be nice to take a look at touchEvents (https://developer.mozilla.org/pt-BR/docs/Web/Events/touchstart)
This should be working just fine the first time you click on the textbox. This is when the focus event is triggered, since you're actually 'focusing on' the item. From then on, until you click anywhere outside the element, your item will already have the focus and therefore will not execute the onfocus event.
The main difference is focus event call any time when you will focus on input field like if you use tab button and focused on input field but in case of click you need to click on input field.
I think that it has to do with the fact that the code executed at the click is executed before focusing on the input and affecting a position to the cursor.
On the other hand, when you listen to the focus event, the cursor has already a position and stays at this position.
That's pure personal theory. However, if you want to make it work, I found a great solution that works in Chrome on this question: Use JavaScript to place cursor at end of text in text input element
You need to clear the value of the input, wait for one millisecond, and reapply the value:
$(function() {
$('#test-input').on('focus', function(evt) {
$target = $(evt.target);
var val = $target.val();
$target.val('');
setTimeout(() => {
$target.val(val)
},1)
});
})

How can I fire a Javascript event when a text box is changed but not by the user?

I have a custom tag STRUTS in a JSP set as standard used to handle the calendar and I can't set any type of event here.
This tag render this HTML : <A onmouseover="return true" href="javascript:ShowCalendar('data')> (..img..) </A>**
When you select date on link, this change my text box with the date selected, I need fire my event in this moment.
My textbox struts tag is this <html:text property="data" styleClass="testo10" size="12" maxlength="10" tabindex="3"/>
I tried with onchange event, but this work only if user do the changes.
I need fire event whenever the textbox is changed whether the user is or not(changes from Javascript for example or from link, like in my case).
How can I do that?
This can be achieved with 'input' event.
<input type="text" class="txtTest" value="test" onchange="textChange();" oninput="this.onchange();"/>
Here I used jQuery to trigger 'input' event and setTimeout() to just mimic text change dynamically.
function textChange(){
alert('text change');
}
setTimeout(function(){
$('.txtTest').val('new text').trigger("input");
},2000);
JS Bin link here
Basically .trigger() method of jQuery help to trigger the event which you want to fire. In this case I'm firing 'input' event of textbox, which in return calling it's own onchange() method. Or simple you can directly trigger change event also.
Another Solution
For IE7 support
jQuery 1.x + textchange plugin help to achieve this.
I tried with IE7 Emulation.
<input type="text" id="txtTest" value="test"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://zurb.com/playground/uploads/upload/upload/5/jquery.textchange.min.js"></script>
<script type="text/javascript">
$('#txtTest').bind('textchange', function (event, previousText) {
alert(previousText);
});
setTimeout(function(){
$('#txtTest').val('new text').trigger('textchange','some data');
},3000)
</script>
Bind change event in javascript
document.getElementById('txtbox_id').addEventListener('change', function() {
alert("text changed"); //or do whatever u want here
});

How to trigger a jquery plugin after a keyup event from an inline script

In this fiddle you can see the script I am working on that uses this plugin to create estimates. However, this plugin only allows predetermined values in data-attributes to be used in checkbox and radiobutton inputs. However, I need to be able to enter values for what I want to use it for, so I created a field that uses keyup to change the data-attribute named data-cost. This method does update the data-attributes, but does not trigger the script to sum the new values entered.
I wanted to know if there was a edit the plugin or trigger it outside the script when they keyup event happens.
This is the keyup script
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));
calculateTotalFor() // this is how I do it on inline scripts
}, 0)
})
});
This is the input that has the data-attribute changed from the keyup event.
<input type="checkbox" checked="checked" data-cost="100" debt="" value="" name="f_2[]"/>
This is the input where the value is entered for the keyup event
<input type="text" maxlength="7" class="balance" id="account_balance1" name="cardbalance" value=""/>
By checking the plugin source, this solves your problem:
$("input[data-cost][debt]").data('cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").data('debt',str.replace(/^\$/, ''));
$('#jquery-order-form').data('jprice').onChange();
The problem is that you updated the html attributes, but not the inner data.
Here you have it working:
http://jsfiddle.net/edgarinvillegas/8jdfJ/3/
Cheers, from La Paz, Bolivia

Categories

Resources