Disabling a dropdown if a Textfield contains a certain value - javascript

I have an issue with HTML and Javascript where I'm trying to create a condition that follows the following rules:
If the first text-box contains a certain word, disable the following drop-down.
If it doesn't contain that certain word, keep it enabled.
So far, I've got this code
var noSample = "HW8020";
const interval = setInterval(function() {
// method to be executed;
function codeCheck() {
var x = document.getElementById("form-RequestAQuoteUK-9bbb_Products_Interest_Value").value;
}
function validateSample() {
if ( x == noSample) {
document.getElementById(
"form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue"
).disabled = true;
} else {
document.getElementById(
"form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue"
).disabled = false;
}
}
}, 5000);
The noSample variable being the code that, when input into the text-field, will disable the dropdown. The Ids weren't my choice of naming, but I'm new to Javascript and am trying to fix an issue with the company I work for!
Any ideas?

You should rather use event input instead of setInterval and use indexOf to check if input.value contains certain value.
var noSample = "HW8020";
let input = document.getElementById(
"form-RequestAQuoteUK-9bbb_Products_Interest_Value",
);
input.addEventListener("input", () => {
validateSample(input.value)
});
function validateSample(inputValue) {
let selectEl = document.getElementById(
"form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue",
);
if (inputValue.indexOf(noSample) > -1) {
selectEl.disabled = true;
} else {
selectEl.disabled = false;
}
}

As suggested in the comments, you can add an event listener to your Products_Interest_Value input and then enable or disable the dropdown based on whether or not this matches your noSample value.
const noSample = "HW8020";
document.querySelector("#form-RequestAQuoteUK-9bbb_Products_Interest_Value").addEventListener("input", e => {
document.querySelector("#form-RequestAQuoteUK-9bbb_DropDown_Samples_SelectedValue").disabled = (e.target.value == noSample);
});

Related

JS - Add class to form when input has value

I have a form with one input field for the emailaddress. Now I want to add a class to the <form> when the input has value, but I can't figure out how to do that.
I'm using this code to add a class to the label when the input has value, but I can't make it work for the also:
function checkForInputFooter(element) {
const $label = $(element).siblings('.raven-field-label');
if ($(element).val().length > 0) {
$label.addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
Pen: https://codepen.io/mdia/pen/gOrOWMN
This is the solution using jQuery:
function checkForInputFooter(element) {
// element is passed to the function ^
const $label = $(element).siblings('.raven-field-label');
var $element = $(element);
if ($element.val().length > 0) {
$label.addClass('input-has-value');
$element.closest('form').addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
$element.closest('form').removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
I've updated your pen here.
Here it is, using javascript vanilla. I selected the label tag ad form tag and added/removed the class accoring to the element value, but first you should add id="myForm" to your form html tag. Good luck.
function checkForInputFooter(element) {
// element is passed to the function ^
let label = element.parentNode.querySelector('.raven-field-label');
let myForm = document.getElementById("myform");
let inputValue = element.value;
if(inputValue != "" && inputValue != null){
label.classList.add('input-has-value');
myForm.classList.add('input-has-value');
}
else{
label.classList.remove('input-has-value');
myForm.classList.remove('input-has-value');
}
}
You can listen to the 'input' event of the input element and use .closest(<selector>) to add or remove the class
$('input').on('input', function () {
if (!this.value) {
$(this).closest('form').removeClass('has-value');
} else {
$(this).closest('form').addClass('has-value');
}
})
Edit: https://codepen.io/KlumperN/pen/xxVxdzy

IF condition need to check evrytime

I am using the below code to render the same as many as times,
I have two sections, one section with show-all class and another with no class.
When 'show-all' class is not available, it need to run countIncrease function, if class available no need to run the function,
In every time section need to check whether the class is available or not.
class Grid {
init() {
$('.grid').each(function() {
const $this = $(this);
// getting values & url from from html
const dropDownUrlpath = $this.find('.grid__dropdown-select').attr('data-ajaxurl');
const hasClass = $this.find('.grid').hasClass('grid_showall');
// countIncrease shows the inital 6 compoents/div and rest of will be hidden
// onclick it will display 3 components/div
function countIncrease() {
let limit = parseInt($this.find('.grid__component').attr('data-initcount'), 10);
const incrementalCall = parseInt($this.find('.grid__component').attr('data-incrementalcount'), 10);
$this.find(`.grid__content > .grid__component:gt(' ${limit - 1} ') `).hide();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
else {
$this.find('.grid__cta').show();
}
$this.find('.grid__cta').on('click', function(event) {
event.preventDefault();
limit += incrementalCall;
$this.find(`.grid__content > .grid__component:lt(' ${limit} ')`).show();
if ($this.find('.grid__content > .grid__component').length <= limit) {
$this.find('.grid__cta').hide();
}
});
}
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
// on dropdown change taking the selected dropdown value and adding #end of the url and replacing the previous html
$this.find('.grid__dropdown-select').on('change', function() {
const optionValue = this.value;
$.ajax({
url: dropDownUrlpath + optionValue,
success(result) {
$this.find('.grid__content').html(result);
countIncrease();
}
});
});
});
}
}
I written if condition, but it running once and giving false condition in both the scenarios,
if (hasClass.length === true ) {
console.log('class exist-----'+ hasClass);
countIncrease();
}
How to handle it...?
shouldnt you add a parameter to the .hasClass so it knows what to check?
if ( $this.hasClass ('some class') === true ) {
alert('something');
}
or set if(hasClass.length > 0){}
keep the checking class in a variable by finding with parent div,
const hasClass = $this.find('.grid').hasClass('grid_showall');
gets the attribute value for only the first element in the matched set with .attr() method
const classInthis = hasClass.attr('class');
check the condition, with
if (classInthis !== 'grid_showall') {
countIncrease();
}

JavaScript force an OnChange in Maximo

I'm currently working on a Bookmarklet for Maximo, which is a Java EE application, and I need to populate a few input boxes.
Generally when a use inputs data into the box they click a button that gives them a popup and they search for the value to be added to the script. Or they can type the name and hit tab/enter and it turns it to capital letters and does a few things in the background (not sure what it does exactly).
I currently use
Javascript: $('mx1354').value = "KHBRARR"; $('mx1354').ov= "KHBRARR";
But it does not work like I need it to. It set's the input box to the value needed, but it doesn't run the background functions so when I hit the save button it doesn't recognize it as any changes and discards what I put into the box.
How could I simulate a tab/enter button has been pressed?
So far I've tried to call the onchange, focus/blur, and click functions (Not 100% sure if I called them correctly).
The dojo library is part of the application, so I'm not sure if I can use one if it's feature or if jQuery would cause a conflict.
P.S. This needs to run in IE.
The OnChange Function:
function tb_(event)
{
event = (event) ? event : ((window.event) ? window.event : "");
if(DESIGNMODE)
return;
var ro = this.readOnly;
var exc=(this.getAttribute("exc")=="1");
switch(event.type)
{
case "mousedown":
if(getFocusId()==this.id)
this.setAttribute("stoptcclick","true");
break;
case "mouseup":
if (isIE() && !hasFocus(this))
{
this.focus();
}
if (isBidiEnabled)
{
adjustCaret(event, this); // bidi-hcg-AS
}
break;
case "blur":
input_onblur(event,this);
if (isBidiEnabled) // bidi-hcg-SC
input_bidi_onblur(event, this);
break;
case "change":
if(!ro)
input_changed(event,this);
break;
case "click":
if(overError(event,this))
showFieldError(event,this,true);
var liclick=this.getAttribute("liclick");
var li=this.getAttribute("li");
if(li!="" && liclick=="1")
{
frontEndEvent(getElement(li),'click');
}
if(this.getAttribute("stoptcclick")=="true")
{
event.cancelBubble=true;
}
this.setAttribute("stoptcclick","false");
break;
case "focus":
input_onfocus(event,this);
if (isBidiEnabled) // bidi-hcg-SC
input_bidi_onfocus(event, this);
this.select();
break;
case "keydown":
this.setAttribute("keydown","true");
if(!ro)
{
if(isBidiEnabled)
processBackspaceDelete(event,this); // bidi-hcg-AS
if(hasKeyCode(event, 'KEYCODE_DELETE') || hasKeyCode(event, 'KEYCODE_BACKSPACE'))
{
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
}
if((hasKeyCode(event, 'KEYCODE_TAB') || hasKeyCode(event, 'KEYCODE_ESC')))
{
var taMatch = dojo.attr(this, "ta_match");
if(taMatch) {
if(taMatch.toLowerCase().indexOf(this.value.toLowerCase()) == 0)
{
console.log("tamatch="+taMatch);
this.value = taMatch;
input_keydown(event, this);
dojo.attr(this, {"prekeyvalue" : ""});
input_forceChanged(this);
inputchanged = false;
return; // don't want to do input_keydown again so preKeyValue will work
}
}
if(this.getAttribute("PopupType"))
{
var popup = dijit.byId(dojohelper.getPopupId(this));
if (popup)
{
dojohelper.closePickerPopup(popup);
if(hasKeyCode(event, 'KEYCODE_ESC'))
{
if (event.preventDefault)
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
return;
}
}
}
}
input_keydown(event,this);
datespin(event,this);
}
else if(hasKeyCode(event,'KEYCODE_ENTER') || (hasKeyCode(event,'KEYCODE_DOWN_ARROW') && this.getAttribute("liclick")))
{
var lbId = this.getAttribute("li");
frontEndEvent(getElement(lbId), 'click');
}
else if(hasKeyCode(event,KEYCODE_BACKSPACE))
{
event.cancelBubble=true;
event.returnValue=false;
}
break;
case "keypress":
if(!ro)
{
if(event.ctrlKey==false && hasKeyCode(event,'KEYCODE_ENTER'))
{
var db = this.getAttribute("db");
if(db!="")
{
sendClick(db);
}
}
}
break;
case "keyup":
var keyDown = this.getAttribute("keydown");
this.setAttribute("keydown","false");
if(event.ctrlKey && hasKeyCode(event,'KEYCODE_SPACEBAR'))
{
if(showFieldError(event,this,true))
{
return;
}
else
{
menus.typeAhead(this,0);
}
}
if(!ro)
{
if(isBidiEnabled)
processBidiKeys(event,this); // bidi-hcg-AS
numericcheck(event,this);
var min = this.getAttribute("min");
var max = this.getAttribute("max");
if(min && max && min!="NONE" || max!="NONE")
{
if(min!="NONE" && parseInt(this.value)<parseInt(min))
{
this.value=min;
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
this.select();
return false;
}
if(max!="NONE" && parseInt(this.value)>parseInt(max))
{
this.value=max;
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
this.select();
return false;
}
}
var defaultButton = false;
if(event.ctrlKey==false && hasKeyCode(event,'KEYCODE_ENTER'))
{
var db = this.getAttribute("db");
if(db!="")
{
defaultButton=true;
}
}
input_changed(event,this);
}
else
{
setFocusId(event,this);
}
if(showFieldHelp(event, this))
{
return;
}
if(keyDown=="true" && hasKeyCode(event, 'KEYCODE_ENTER') && !event.ctrlKey && !event.altKey)
{
menus.typeAhead(this,0);
return;
}
if(!hasKeyCode(event, 'KEYCODE_ENTER|KEYCODE_SHIFT|KEYCODE_CTRL|KEYCODE_ESC|KEYCODE_ALT|KEYCODE_TAB|KEYCODE_END|KEYCODE_HOME|KEYCODE_RIGHT_ARROW|KEYCODE_LEFT_ARROW')
&& !event.ctrlKey && !event.altKey)
{
menus.typeAhead(this,0);
}
break;
case "mousemove":
overError(event,this);
break;
case "cut":
case "paste":
if(!ro)
{
var fldInfo = this.getAttribute("fldInfo");
if(fldInfo)
{
fldInfo = dojo.fromJson(fldInfo);
if(!fldInfo.query || fldInfo.query!=true)
{
setButtonEnabled(saveButton,true);
}
}
window.setTimeout("inputchanged=true;input_forceChanged(dojo.byId('"+this.id+"'));", 20);
}
break;
}
}
After some time I found that in order to make a change to the page via JavaScript you need to submit a hidden form so it can verify on the back-end.
Here is the code I used to change the value of Input fields.
cc : function(e,v){
e.focus(); //Get focus of the element
e.value = v; //Change the value
e.onchange(); //Call the onchange event
e.blur(); //Unfocus the element
console.log("TITLE === "+e.title);
if(e.title.indexOf(v) != -1) {
return true; //The value partially matches the requested value. No need to update
} else {
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = e.id;
inputs.namedItem("changedcomponentvalue").value = v;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
}
//Value isn't set to the required value so pass false
return false;
}
run this
input_changed(null,document.getElementById('IDHERE'));
In maximo 7.5 i built a custom lookup
when i click the colored hyperlink java script is called to update the values back to parent form values or updated but on save the value or not updated
function riskmatrix_setvalue(callerId, lookupId, value,bgrColor,targetid){
if (document.getElementById(callerId).readOnly){
sendEvent('selectrecord', lookupId);
return;
}
textBoxCaller = document.getElementById(callerId);
//dojo.byId(callerId).setAttribute("value", value);
//dojo.byId(callerId).setAttribute("changed", true);
//dojohelper.input_changed_value(dojo.byId(callerId),value);
//textBoxCaller.style.background = bgrColor;
//var hiddenForm = getHiddenForm();
//if(!hiddenForm)
// return;
//var inputs = hiddenForm.elements;
//inputs.namedItem("event").value = "setvalue";
//inputs.namedItem("targetid").value = dojo.byId(callerId).id;
//inputs.namedItem("value").value = value;
//sendXHRFromHiddenForm();
textBoxCaller.focus(); //Get focus of the element
textBoxCaller.value = value; //Change the value
textBoxCaller.onchange(); //Call the onchange event
textBoxCaller.blur(); //Unfocus the element
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = textBoxCaller.id;
inputs.namedItem("changedcomponentvalue").value = value;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
sendEvent("dialogclose",lookupId);
}
Description
I changed a bit #Steven10172's perfect solution and made it into a Javascript re-usable function.
Made this into a separate answer since my edits to the original answer where i added this were refused :)
I also had to change the line e.onchange() to e.onchange(e) because otherwise the textbox handler (tb_(eventOrComponent) function) would throw TypeError: textbox.getAttribute is not a function.
Code
var setFakeValue = function(e,v){
console.log("Changing value for element:", e, "\nNew value:", v);
e.focus(); //Get focus of the element
e.value = v; //Change the value
e.onchange(e); //Call the onchange event
e.blur(); //Unfocus the element
if(e.title.indexOf(v) != -1) {
return true; //The value partially matches the requested value. No need to update
}
else {
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = e.id;
inputs.namedItem("changedcomponentvalue").value = v;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
}
//Value isn't set to the required value so pass false
return false;
}
Usage
setFakeValue(html_element, new_value);
Fun fact
I spent a lot of time searching for a solution to programmatically change an <input> value in Maximo... At some point i got really frustrated, gave up and started to think it just wasn't possible...
Some time ago i tried to search with no expectations at all and after some time i found the solution... Here...
Now... As you can see this is literally just a total copy of StackOverflow, including questions and solutions (marking the upvotes with plain text lol), but in Chinese... This got me curious and after a little search i found this post on StackOverflow..
High five to Chrome built-in webpage translator that let understand something on that page ^^

Compare onclick action of two html button using javascript

I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?
This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}
Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/

jQuery: dealing with multiple keypress listeners?

I have a page that needs to do two things at once:
Listen all the time for input from a scanner (which presents as keyboard input), and notice when a string is entered in the right format.
Listen for a user focussing on a particular dropdown, and typing a set of initials - when a set of initials is entered that matches the title attribute of an item in the dropdown, focus on that dropdown.
I can do either of these things separately, but not together. Code:
// Listen for input when userlist is in focus.
$("#userlist").keypress(function (e) {
initials += String.fromCharCode(e.which).toUpperCase();
$(this).find("option").filter(function () {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().attr("selected", true);
// uses timer to check for time between keypresses
return false;
});
// Listen for scanner input all the time.
var input = '',
r1 = /^~{1}$/,
r2 = /^~{1}\d+$/,
r3 = /^~{1}\d+\.$/,
r4 = /^~{1}\d+\.\d+$/,
r5 = /^~{1}\d+\.\d+~{1}$/;
$(window).keypress(function(e) {
// when input matches final regex, do something
}
If I have both, then while the user is focussed on the dropdown, the page does not 'hear' the input from the scanner.
How can I combine the two together to make sure the page reacts to scanner input, even while the user is focussed on the dropdown?
It's because you are overriding the listener on the window object with a listener on the keypress object. I would do something like this:
var input = '',
r1 = /^~{1}$/,
r2 = /^~{1}\d+$/,
r3 = /^~{1}\d+\.$/,
r4 = /^~{1}\d+\.\d+$/,
r5 = /^~{1}\d+\.\d+~{1}$/;
function checkRegex(e) { /* Check */ }
// Listen for input when userlist is in focus.
$("#userlist").keypress(function (e) {
checkRegex(e);
initials += String.fromCharCode(e.which).toUpperCase();
$(this).find("option").filter(function () {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().attr("selected", true);
// uses timer to check for time between keypresses
return false;
});
// Listen for scanner input all the time.
$(window).keypress(function(e) {
checkRegex(e);
}
Wouldn't delegate give you the necessary control? You could then check for the event target and respond accordingly?
ie:
$(window).delegate('keypress', function(e){
if ($(e.target).attr('id') == 'userlist'){
// something
}else{
//something else
}
});
You don't need two handlers. Just have a single handler at the window level and then check which element raised the event:
$(window).keypress(function(e) {
var $target = $(e.target);
if ($target.is("#userlist")) {
initials += String.fromCharCode(e.which).toUpperCase();
$(this).find("option").filter(function () {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().attr("selected", true);
// uses timer to check for time between keypresses
return false;
} else {
// when input matches final regex, do something
}
});
This is probably way more complex than you'd like it to be, but I think it'll fit your purpose.
I tried to make it in the style of a jQuery plugin, and allow you to attach it to any specific object (and customize of it should override bubbling up through the DOM (in the case of your combo box) in addition to allow for windows, etc.
Anyways, try it out and see what you think. I can make modifications if necessary, just need to know what they are.
Working Example: http://www.jsfiddle.net/bradchristie/xSMQd/4/
;(function($){
$.keyListener = function(sel, options){
// avoid scope issues by using base instead of this
var base = this;
// Setup jQuery DOM elements
base.$sel = $(sel);
base.sel = sel;
base.keyPresses = '';
base.validater = null;
// add a reverse reference to the DOM object
base.$sel.data('keyListener', base);
// create an initialization function we can call
base.init = function(){
base.opts = $.extend({}, $.keyListener.defaultOptions, options);
base.$sel.keypress(function(e){
base.keyPresses += String.fromCharCode(e.which);
if (base.validator != null)
clearTimeout(base.validator);
if (base.keyPresses != '')
base.validator = setTimeout(base.validateInput, base.opts.callbackDelay);
if (base.opts.preventDefault)
e.preventDefault();
else if (base.opts.stopPropagation)
e.stopPropagation();
});
};
base.validateInput = function(){
var filter = base.opts.filter;
var reCompare = (typeof(filter)=='object'
? filter.constructor.toString().match(/regexp/i)!==null
: false);
// exception when the input is cleared out
var input = base.sel.constructor.toString().match(/HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement/i);
if (input && (!base.opts.preventDefault && base.$sel.val() == ''))
base.keyPresses = '';
// regular expression match
if (reCompare){
if (base.keyPresses.match(filter))
base.validateSuccess();
else
base.validateFailure();
// traditional string match
}else if (typeof(filter)=='string'){
if (base.keyPresses==filter)
base.validateSuccess();
else
base.validateFailure();
}
// reset string
base.keyPresses = '';
};
base.validateSuccess = function(){
if (typeof(base.opts.success)=='function')
base.opts.success(base.keyPresses);
};
base.validateFailure = function(){
if (typeof(base.opts.failure)=='function')
base.opts.failure(base.keyPresses);
};
// run the initializer
base.init();
};
$.keyListener.defaultOptions = {
// time to wait before triggering callback
// Give it time to accumulate the key presses and send it off
// as a compiled package
callbackDelay: 1000,
// Filter to apply to the input (can be a string match or a regular expression)
filter: /.*/,
// functions to callback when a match has or hasn't been made
success: function(i){},
failure: function(i){},
// would you like this to completely override key input?
preventDefault: false,
// stop it from going up the DOM tree (first object to grab the keypress
// gets it)
stopPropagation: true,
};
$.fn.extend({
keyListener: function(options){
// use return to allow jQuery to chain methods
return this.each(function(){
(new $.keyListener(this, options));
});
}
});
})(jQuery);
$('#listen-scanner,#listen-combo,#listen-text').add(window).keyListener({
filter: /^\d+$/,
success: function(input){
$('#output-scanner').text('Match!: '+input);
},
failure: function(input){
$('#output-scanner').text('No Match: '+input);
},
stopPropagation: true
});
And the HTML I tried it on:
<input type="text" id="listen-scanner" /><span id="output-scanner"></span><br />
<select id="listen-combo">
<option value="AA">Aardvarc</option>
<option value="AB">Abracabra</option>
<option value="AC">Accelerate</option>
<option value="AD">Adult</option>
</select><span id="output-combo"></span>
<textarea id="listen-text"></textarea>

Categories

Resources