I have a select2 dropdown.
<select class="eselect2" type="text" id="qename" style="width: 390px;">
<option value="1">NY</option>
<option value="2">MA</option>
<option value="3">PA</option>
<option value="4">CA</option>
</select>
with simple javascript
$( document ).ready(function() {
console.log( "ready!" );
$(".eselect2").select2();
$('.select2-search__field').on("keydown", function(e) {
console.log(e.keyCode); // nothing happens
if (e.keyCode == 13) {
}
});
});
I have an event associated with keypress on the input field. It does not get fired since, the textbox is destroyed and recreated each time the dropdown arrow in the select2 is clicked.
I have attached a fiddle for clarity.
http://jsfiddle.net/sizekumar/ckfjzkhj/
Really jQuery keypress event doesn't fire on input.select2-search__field element. But pure js event does. This piece of code works for me
document.getElementsByClassName('select2-search__field')[0].onkeypress = function(evt) { console.log(evt); }
EDIT: This doesn't solve the problem.
I wouldn't call this a duplicate, but I think this answer directly applies: https://stackoverflow.com/a/30697173/5948237
$('.select2-input').on("keydown", function(e) {
if (e.keyCode == 13) {
}
});
Related
I have a select that is bound to a change event so that it will take the user to a new page when a selection is made. It's fine with the mouse, but when I try to make a selection using my keyboard's arrow keys, the change event fires as soon as I press the arrow rather than waiting for me to tab out, so I can only ever select the first option with my keyboard.
$selectLocation.on('change', function() {
location.href = '/data#' + $(this).val().toUpperCase();
});
How can I differentiate between a click and a keypress on my change function, or otherwise make the change function not fire on keypress?
Consider the following snippet:
// Sets the redirect based on user activity on #test.
$('#test').on('change', function(e) {
if ($(this).data('clicked')) {
// A click was used to change the select box, redirect.
console.log('clicked redirect');
}
});
// Sets data-keypressed on #test when the down or up arrow key is pressed.
$('#test').on('keydown', function(e) {
var code = e.keyCode || e.which;
if (code === 38 || code === 40) {
// Reset data-clicked.
$(this).data('clicked', false);
// Bind focusout to the redirect.
$('#test').unbind('focusout').bind('focusout', function(e) {
if ($(this).val !== '') {
// An option is selected.
console.log('keyboard focusout redirect');
}
});
}
});
// Sets data-clicked on #test.
$('#test').on('click', function(e) {
// Unbind the focusout event added in the change handler.
$(this).unbind('focusout');
// Set data-clicked to be used in the change handler.
$(this).data('clicked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test" data-clicked="false">
<option value="">-- Select an Option --</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
This snippet uses the HTML data attribute to set whether or not the select box was changed with a click, and sets the focusout event on the select box when the select box was changed on keypress. The redirect will occur immediately on click selection, but when using the keyboard will only occur when the select box is focused out and a value is selected.
As selection causes (in your case) navigation, the simplest solution is to avoid change event. Instead save initial value and compare against current when clicked or blured.
var defaultValue = $('#select').val();
$('#select').focus();
$('#select').on('click blur', function(event) {
if (defaultValue === $(this).val()) {
return
}
// no need to save with location.href
defaultValue = $(this).val()
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="option" id="select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="s">
<option value="1">selected1</option>
<option value="2">selected2</option>
<option value="3">selected3</option>
<option value="4">selected4</option>
</select>
<div id="se">
</div>
$('body').on('change', '#s', function() {
$('#se').text($('#s :selected').text()+" / unfortunatly it also triggers when Im moving with the UP and DOWN keys, not just with select");
});
https://jsfiddle.net/8kLke2je/
I want this event triggered if I pick an item from the dropbox with mouseclick and not with UP and DOWN arrows.
Just use the "click" event on the select:
$('#s').click(function(){
var sv = $('#s').val();
$('#se').html("That\'s it: "+sv);
});
Here there is a fiddle for it: https://jsfiddle.net/nemoneminis/rwza9xzt/1/
.on passes the event into the callback function. You can utilize that to detect whether it was a click or keypress.
If you bind separately to click and keyup, you can detect which one by checking the event type:
$(document).on('click keyup', '#s', function(e) {
if ('click' == e.type) {
$('#se').text($('#s :selected').text());
}
});
$('#selectmenu').on('keyup focus mousedown', function(e) {
e.preventDefault();
});
but when it is selected by pressing tab i can change the value by pressing up & down key.how to stop it?
Block the tab key.
$('/*The Previous Input */').on('keydown', function(e) {
if (e.keyCode == 9) {
e.preventDefault();
}
});
I don't have your HTML, so i can't test or integrate the code.
You also can use disabled="disabled", i think is a better solution.
You use off() or unbind() methods of jQuery:
<select id="dropDown" name="dropDown" style="margin-top: 5px; width: 150px;">
<option value="select">Select </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="All">All </option>
</select>
<button id="stopChange" >Stop</button>
<button id="StartChange" >Start</button>
jQuery code:
$("#stopChange").click(function () {
$("#parSelCategor").unbind("change");
});
$("#StartChange").click(function () {
$("#parSelCategor").bind("change");
});
You may listen you a more global event like 'onchange' and change the value back to the previous one when the event trigger.
Disabling the select may work too.
Edit : 'keydown' seems like a good idea too.
you can change the tabindex of the select box
$('#selectmenu').attr('tabindex', -1).on('keyup focus mousedown', function (e) {
e.preventDefault();
});
or best way is just disable the control
$('#selectmenu').attr("disabled", true);
Demo
Here's a solution that simply forces the selection to stay the same if some variable (stopChange) is true.
JS (jQuery):
var stopChange = true;
var opt = $('option:selected');
$('#selectmenu').on('change', function () {
if (stopChange) {
opt.attr('selected', true);
}
});
Here's a fiddle.
I have this HTML:
<select id="select-one">
<option value="">Choose</option>
<option value="1">House</option>
</select>
<select id="select-two">
<option value="">Choose</option>
<option value="A">Table</option>
</select>
And this Javascript with JQuery
$("#select-two").focus( function() {
if( $("#select-one").val() == "" ) {
alert("Fill select-one first!");
return false;
}
});
So i am getting a infinite loop with alerts because after call alert() Javascript puts the focus again in the same select (select-two).
Someone can help me to solve this please?
Note: based on your comments, this assumes you must listen to the focus event.
Solution 1 - using blur() - effective but buggy in Chrome
In theory, the focus event is not cancelable, so return false or event.preventDefault() will have no effect in this case. However, in practice, you can reverse the event by using the blur() method.
For example:
$('#select-two').on('focus',function () {
if ($("#select-one").val() == "") {
$(this).blur();
alert('Fill select-one first!');
return false;
}
});
See jsFiddle demo
This effectively prevents the field from regaining focus after the alert call and so the focus event is not repeated. The only problem is that in Chrome even though the field is not focused anymore, the dropdown remains open (see demo).
Solution 2 - using remove() and clone() - costly but cross-browser
If Chrome's behavior is problematic, you can take a more crude approach, whereby you remove() the select from the DOM, clone() it and then reinsert it into the DOM. This will effectively "reset" the select element completely, leaving it without focus as well as closed.
For example:
$(document).on('focus','#select-two',function (e) {
if ($("#select-one").val() == "") {
$(this).remove().clone().insertAfter('#select-one');
alert('Fill select-one first!');
return false;
}
});
See jsFiddle demo
The upside of this approach is that it works well in Chrome too. The downside of this approach is that it involves manipulating the DOM for a very trivial issue.
I think you need an extra event that change content select-two when the value of select-one has "" like this:
HTML
<select id="select-one">
<option value="">Choose</option>
<option value="1">House</option>
</select>
<select id="select-two">
<option value="">Choose</option>
<option value="A">Table</option>
</select>
JS
$("#select-one").change(function() {
if ($(this).val() == "") {
$("#select-two").val("");
}
});
$("#select-two").focus(function() {
if( $("#select-one option:selected").val() == "" ) {
alert("Fill select-one first!");
$("#select-one").focus();
return false;
}
});
Demo
Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
http://jsfiddle.net/x7HVQ/
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
heres a jquery plugin to do that
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
to use it, include the code and set it up like this:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
jsfiddle of it here http://jsfiddle.net/VrwgP/30/
It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.
Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If your input is search, you also can use on 'search' event. Example
<input type="search" placeholder="Search" id="searchTextBox">
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
//Short and simple solution
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
Another subtle variation.
I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup or keydown event to catch a press of the enter button.
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
<input type="text" name="search" id="search">
</form>
<script>
function doSomething(event){
let $val = $('form#searchForm input[name="search"]').val();
console.log($val);
event.preventDefault();
}
</script>
One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.