How to activate function after the keypress? - javascript

Im building a autocomplete tool for my website. I want it to search for partial matches (it works only when "*" is the last character)
So I have this code:
<script type="text/javascript">
$('.search-form').click(function () {
var self = this;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var searchfield = $('.input-block-level');
searchfield.val(searchfield.val() + "*");
self.submit();
});
</script>
What it does is it gives me "*" immediately after clicking in search field and submits.
I need the function that puts the asterisks as the last symbol immediately after clicking (so when person starts typing the "*" is the last character) and waits for person to click submit (or not).
Any ideas anyone?
Please help

I'm assuming the .search-form that is being clicked on is the entire form? So when you click within the search box to type, the entire callback function for your click object is being run, which includes the self.submit().
I think you need to separate the two functionalities into their own event handlers. The searchfield.val(searchfield.val() + "*"); should be run when someone clicks into the $('.input-block-level');, and the submit function should be attached to the submit button itself.

What you are looking for, if I understood correctly, is an additional event listener for the keypress or keyup event. But you have to replace the asteriks every time the event fires. Try this:
$('.input-block-level').keypress(function(e) {
e.preventDefault();
e.stopPropagation();
if(/[a-z]/ig.test(e.key)) {
$(this).val($(this).val().replace(/\*$/g,'') + e.key + '*');
}
});

Related

js - trigger generic function on space bar press anywhere on document

I have a colour guessing game with six different colour squares and an rgb code at the top of the page. The game works and the game resets via function - resetUI() - when a reset button on the page is clicked.
However, I want to trigger the resetUI function whenever the space bar is pressed. I have the following code, it doesn't throw any errors but it also doesn't work:
var body = document.querySelector("body");
body.addEventListener("keydown",function(){
if(this.key === " "){
resetUI();
}
});
I am fairly certain my use of "this" is wrong but I can't think of an alternative.
I have searched MDN and stackOverflow but I haven't seen a solution to this problem. Thanks.
key belongs to the event (which is passed into the event handler), not the body (which is what this refers to).
The next problem you will have is when you add an input or textarea to the page and anytime the user put a space into the input it will run your function.. You can check against the target to make sure the input isn't receiving the keystroke before you fire your function..
var body = document.querySelector("body");
body.addEventListener("keydown",function(e){
var isInput = ~["TEXTAREA", "INPUT"].indexOf(e.target.tagName);
if(e.key === " " && !isInput){
// resetUI();
console.log("u clicked spacebar, and it wasn't in an input");
}
});
<input />
You have lot of unnecessary code. And you should receive the event object from callback function to check against which key got pressed.
To check spacebar you shouldn't check against " " instead you have to check the keyCode of event.
document.body.onkeydown = function(e){
if(e.keyCode == 32){
console.log("space bar pressed");
resetUI();
}
}

Change event is fired once for a select if dialog is escaped or clicked out side

I am trying to write this simple Javascript logic to disable multiselect field if user chose specific options from another select field. This is a JIRA dialog2, so I am using their JQuery namespace (eg: AJS).
Problem is when I open the dialog and select the specific values from the select field the handler for the change event of the select field runs properly and the other multiselect field is disabled. However, the snippet is not called/doesn't run if the dialog got closed by either pressing escape button or clicking outside it, as opposed to closing it by clicking the 'close' button. I am not a js expert and would appreciate any help in this.
(function($) {
$(function() {
AJS.dialog2.on("show", function(e) {
var targetId = e.target.id;
var spinning = false;
if (targetId == "sr-dialog") {
//start of the part that fails
//noticing that the change event for the searchtypeselect field is fired only when the dialog shows up first time and re shows again only if the dialog got closed by the 'close' button. If dialog escaped it doesn't fire anymore.
var $searchTypeSelect = AJS.$("#select-searchtype");
var $fieldMultiSelect = AJS.$("#field-multiselect");
$searchTypeSelect.change(function(e) {
if ($searchTypeSelect.val() == 'D' || searchTypeSelect.val() == 'S') {
$fieldMultiSelect.removeAttr('disabled');
} else {
$fieldMultiSelect.attr('disabled', 'disabled').val('');
}
}).trigger('change');
// end of the part that fails
AJS.$(e.target).find("#submit-spinner-trigger").click(function(e) {
var number = AJS.$("input[type=radio]:checked", "#topSearchForm").val();
var searchType = AJS.$("#select-searchtype option:selected", "#topSearchForm").val();
var fields = [];
AJS.$("#field-multiselect :selected", "#topSearchForm").each(function(i, selected) {
fields[i] = $(selected).val();
});
var since = AJS.$("#select-since option:selected", "#topSearchForm").val();
if (!spinning) {
AJS.$('.button-spinner').spin();
spinning = true;
}
});
}
});
});
})(AJS.$);
I don't think this is related to JIRA or AUI. It's just a javascript question.
You'd like to handle an event when a dialog gets 'closed' by clicking 'escape' or the 'x' at the top. These posts answer that:
Hook into dialog close event
How to handle ESC keydown on javascript popup window
Thanks GlennV. It is that actually and also hooking the event handler to the specific item on the screen helped fix the issue.
Answered here

fire jquery focus out when only the input focus is changed

I use the following code to add the selected div value into a input.
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
$('.del').click(function(e){
e.preventDefault();
e.stopPropagation();
//addOrRemoveWatermark(lastFocus);
$(lastFocus).val(function(index, text){
return text.replace(/(\s+)?.$/, '');
});
})
below is a sample image if the input panel I have! This is developed for a touch device and hence the key pad.
The script works fine to add value on each button press in the keypad. The problem I'm facing is for the room number I want to run an ajax call after the user has entered the amount. But since the focus is removed every button click, how can I run the script when the focus is changed to another input. I tried the jquery .focusout() method but it gets fired each and every time the user clicks on a number button.
if anyone can suggest me a work around that would be a great help!
thank you!
Perhaps you could delay the request with something like the following:
var roomNoChanged = false;
$('#room-number').change(function() {
roomNoChanged = true;
});
$('#table-number, #no-of-guests').focus(function() {
if(roomNoChanged) {
roomNoChanged = false;
$.post(...)
}
});

onkeypress on a <a> tag

I'm trying get my <a> tag triggered when the user press on the "enter" key. (onkeypress).
my <a> tag:
<a href="javascript:search()" onkeypress="return runScript(event)">
this is my javascript :
function runScript(e)
{
if (e.keyCode == 13) {
alert("dssd");
return false;
}
}
I dont know whats messed up ?
its work for me
Open in new window using javascript
javaScript
window.runScript = function (e) {
if (e.keyCode == 13) {
alert('ss');
return false;
}
else {
return true;
}
}
window.search = function () {
alert('s');
}
live demo : fiddle
Write your html as given below. Note the property tabindex which makes the a tag focusable in certain browsers.
<a id="link" href="http://google.com" onkeydown="runScript(event)" tabindex="1">I am a link</a>
If you need an autofocus on load, you can use the jQuery function focus as shown below.
$(document).ready(
function(e){
$("#link").focus();
}
);
Then your function
function runScript(e){
if(e.keyCode == 13){
alert("pressed enter key");
}
}
you have to call e.preventDefault(); (or return false in some browsers) if you want to prevent the link load the link in href.
function runScript(e){
e.preventDefault();
if(e.keyCode == 13){
alert("pressed enter key");
}
return false;
}
see a demo here:
http://jsfiddle.net/diode/hfJSn/9/show press enter key when the page is loaded
The ENTER key actually triggers the onclick event:
<a href="#" onclick="alert('hello!');">
This means that your search() function inside the href will execute before the onkeypress event.
That works in my browser, though I suspect it's not the way to achieve what you actually want to do... (maybe?)
Number one, you probably don't want it to "return" anything, so you can just do onkeypress="runScript(e)" and it'll run. If that function does return a value, it's not gonna go anywhere...
Number two, it's kinda rare that a keydown event would fire on an anchor (<a>) element, unless of course the user tabs through the other elements 'till it has focus and then presses a key (usually the browser will "highlight" the element that currently has keyboard focus, if it's not just the whole page). Are you wanting your script to run when someone presses enter after typing in a search box or something? if so, you probably want to listen for the event on the search box itself, so add it as that element's onkeydown attribute (for example: <input id="mySearchBox" onkeydown="runScript(e)">) if you just want it to run whenever the user presses enter, regardless of focus or typing text into any particular field, just do as edmastermind29's comment said and add the event listener to the whole document.
Have you tried adding this to your script?
document.onkeypress = runScript;

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources