JavaScript force an OnChange in Maximo - javascript

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 ^^

Related

jquery form validation without click -> when ok show div

is it possible to do this automatically. mean when i type text and click on the second textfield autocheck the first one. then when both ok show the div2 and so on.
here is some code
var step1 = function() {
var first = $("#f_name").val();
var last = $("#l_name").val();
var error = false;
if (first == "") {
$("#f_name").next().text("*ErrorMsg");
error = true;
} else {
$("#f_name").next().text("");
}
if (last == "") {
$("#l_name").next().text("*ErrorMsg");
error = true;
} else {
$("#l_name").next().text("");
}
if (error == false) {
$("#send").submit();
$('#div1').show('slow');
} else {
returnfalse;
}
}
var step2 = function() {
var email1 = $("#e_mail").val();
var adress1 = $("#adress").val();
var error2 = false;
if (email1 == "") {
$("#e_mail").next().text("*ErrorMsg");
error2 = true;
} else {
$("#e_mail").next().text("");
}
if (adress1 == "") {
$("#adress").next().text("*ErrorMsg");
error2 = true;
} else {
$("#adress").next().text("");
}
if (error2 == false) {
$("#send2").submit();
$('#div2').show('slow');
} else {
returnfalse;
}
}
$(document).ready(function() {
$('#div1').hide();
$('#div2').hide();
$("#send").click(step1);
$("#send2").click(step2);
});
hope anyone can help me. and sorry for my bad english :)
greatings
The way that I would do it is:
Assign a variable, something like numSteps and set its initial value to 1
onFocus and onBlur, run a function that steps through each field, based on numSteps
If any fields are empty (or however you want to validate them), set error = true
if !error numSteps++
Make all elements up to numSteps visible
Hope this helps
Very crude example, but demonstrates what I was referring to:
http://jsfiddle.net/aSRaN/

Need help in Javascript onChange event

On change of a dropdown value, I need to confirm whether the user wants to change the value or changed it by mistake.
If user clicks on OK then system should apply the modification, otherwise the value should not change.
As of now I have written code as follows:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
return this;
}
}
here am getting the confirm box but regardless of whether if I press OK or Cancel, the dropdown always shows the new value.
check this fiddle
var drop = document.getElementById("dropdownid");
var selected =drop.options[drop.selectedIndex]; //save selection initially
drop.onclick = function (e){
selected = drop.options[drop.selectedIndex]; // save current selection
}
drop.onchange = function (e){
var a = confirm("Do you want to change");
if (a == false) // no need to check for true
{
selected.selected=true; // if cancel, set the existing selected option
}
}
Please try this:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true)
{
return true;
}
if (a == false)
{
return false;
}
}
You can undo the selection like this:
document.getElementById("dropdownid").onchange = function (){
if (!confirm("Do you want to change")) {
if (typeof this.prevVal=='undefined') {
this.prevVal=this.options[0].value;
for (var i=0;i<this.options.length;i++)
if (this.options[i].defaultSelected)
this.prevVal=this.options[i].value;
}
this.value=this.prevVal;
} else {
this.prevVal=this.value;
}
}
Basically you save in an attribute the previously selected value, and you search for the default value if not changed yet.
try using this code
document.getElementById("dropdownid").onchange = function (eve){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
eve.preventDefault();
}
}

Function called at the start of page loading - javascript

I have a problem; for some reason, my function is being called at the start of the webapplication while the page is loading.
My code is as follows
function validateName(element) {
var len = element.value.length;
//checks if the code is than 6 characters
if (len == 0) {
element.style.backgroundColor="red";
if (element.id == "firstname")
{
document.getElementById('firstNameError').style.display = "block";
}
else if (element.id == "lastname") {
document.getElementById('lastNameError').style.display = "block";
}
return true;
} //if == 0
else {
element.style.backgroundColor="green";
if (element.id == "firstname")
{
document.getElementById('firstNameError').style.display = "none";
}
else if (element.id == "lastname") {
document.getElementById('lastNameError').style.display = "none";
}
return false;
} // if != 0
}
The logic of this function is to validate the text boxes where the user enters their name. Basically,the problem i am facing is as soon as I open up my web page, the text boxes are red, and say 'Your first name cannot be blank!' (which is the firstNameError). Then, once I enter the text in my text box, it doesn't change, it still stays red, and displays the error.
This is how i am calling the function:
function init() {
var firstName = initToolTip("firstname", "firstnameTip");
var lastName = initToolTip("lastname", "lastnameTip");
var promoCode = initToolTip("promocode", "promocodeTip");
//opens the TOS window when you click 'terms and conditions' link
document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
//checks the length of the promo code
promoCode.onblur = validatePromoCode(promoCode);
//checks the validity of a name (is not blank)
firstName.onblur = validateName(firstName);
lastName.onblur = validateName(lastName);
//document.getElementById('submitButton').onmousedown = validateForm();
}
I don't understand why it's being called as soon as the page loads, since it's set, to be called onblur.
can anyone suggest ways to fix this?
You need to pass function references to onblur, not the result of immediately calling a function. Change to this:
function init() {
var firstName = initToolTip("firstname", "firstnameTip");
var lastName = initToolTip("lastname", "lastnameTip");
var promoCode = initToolTip("promocode", "promocodeTip");
//opens the TOS window when you click 'terms and conditions' link
document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
//checks the length of the promo code
promoCode.onblur = function() {validatePromoCode(promoCode);};
//checks the validity of a name (is not blank)
firstName.onblur = function() {validateName(firstName);};
lastName.onblur = function() {validateName(lastName);{;
//document.getElementById('submitButton').onmousedown = validateForm();
}
This changes each onblur assignment to take an anonymous function reference that will be executed later when the onblur event happens, not immediately like your current code was doing.
You're not passing the function to onblur in init; you are passing the result of the function.
See the following example:
var Afuntion=function(){
console.log("hello from function");
return 22;
}
Element.onblur=Afunction("something");//Element.onblur is now 22 and
// "hello from function" is logged
Element.onblur=Afunction; //now onblur has a reference to the function
Element.onblur();//this will log "hello from function" and return 22
Youre not using a library like jQuery to make attaching/adding event listeners easy so it's a bit of a pain to set the event listener using pure JS and read the event in the function. There must be some info on SO how to do this already anyway
In your case you could try this:
promoCode.onblur = function(){ validatePromoCode.call(promoCode,promCode);};

How do I call a sub-function from within a function object in javascript

I've checked the related questions on stack overflow, but can't seem to find an answer to my predicament. I'm trying to use a plugin for javascript (Tag it! - Tag Editor) and I need to find a way to call one of its functions "create_choice()" EDIT: at some point after it has been initiated. Is there a way after calling :
$tagit = $("#mytags").tagit();
that I can then call something like
$tagit.create_choice('test123');
Here is a link for the example :
http://levycarneiro.com/projects/tag-it/example.html
Below is the code from the plugin if it is any help
(function($) {
$.fn.tagit = function(options) {
var el = this;
const BACKSPACE = 8;
const ENTER = 13;
const SPACE = 32;
const COMMA = 44;
// add the tagit CSS class.
el.addClass("tagit");
// create the input field.
var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>\n";
el.html (html_input_field);
tag_input = el.children(".tagit-new").children(".tagit-input");
$(this).click(function(e){
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
$(e.target).parent().remove();
}
else {
// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
// This is needed because the input field needs to be of a small size.
tag_input.focus();
}
});
tag_input.keypress(function(event){
if (event.which == BACKSPACE) {
if (tag_input.val() == "") {
// When backspace is pressed, the last tag is deleted.
$(el).children(".tagit-choice:last").remove();
}
}
// Comma/Space/Enter are all valid delimiters for new tags.
else if (event.which == COMMA || event.which == SPACE || event.which == ENTER) {
event.preventDefault();
var typed = tag_input.val();
typed = typed.replace(/,+$/,"");
typed = typed.trim();
if (typed != "") {
if (is_new (typed)) {
create_choice (typed);
}
// Cleaning the input.
tag_input.val("");
}
}
});
tag_input.autocomplete({
source: options.availableTags,
select: function(event,ui){
if (is_new (ui.item.value)) {
create_choice (ui.item.value);
}
// Cleaning the input.
tag_input.val("");
// Preventing the tag input to be update with the chosen value.
return false;
}
});
function is_new (value){
var is_new = true;
this.tag_input.parents("ul").children(".tagit-choice").each(function(i){
n = $(this).children("input").val();
if (value == n) {
is_new = false;
}
})
return is_new;
}
function create_choice (value){
var el = "";
el = "<li class=\"tagit-choice\">\n";
el += value + "\n";
el += "<a class=\"close\">x</a>\n";
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
el += "</li>\n";
var li_search_tags = this.tag_input.parent();
$(el).insertBefore (li_search_tags);
this.tag_input.val("");
}
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
})(jQuery);
I've created a working example at http://jsfiddle.net/nickywaites/DnkBt/ but it does require making changes to the plugin.
Change
$.fn.tagit = function(options) { ...
to
$.fn.tagit = function(options,callback) { ...
Add
if (callback && typeof callback == 'function') {
callback();
}
after
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
Now you can call a function of your choice right after the tagit call:
$tagit = $("#mytags").tagit(yourOptions, function(){
alert('hi')!
});
You can try to add
return this;
right after the function create_choice block. tagit will return itself and you can call make_choice or any function contained in .fn.tagit

Cycle Focus to First Form Element from Last Element & Vice Versa

I have created a form with malsup's Form Plugin wherein it submits on change of the inputs. I have set up my jQuery script to index drop down menus and visible inputs, and uses that index to determine whether keydown of tab should move focus to the next element or the first element, and likewise with shift+tab keydown. However, instead of moving focus to the first element from the last element on tab keydown like I would like it to, it moves focus to the second element. How can I change it to cycle focus to the actual first and last elements? Here is a live link to my form: http://www.presspound.org/calculator/ajax/sample.php. Thanks to anyone that tries to help. Here is my script:
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
var shiftDown = false;
$('input, select').each(function (i) {
$(this).data('initial', $(this).val());
});
$('input, select').keyup(function(event) {
if (event.keyCode==16) {
shiftDown = false;
$('#shiftCatch').val(shiftDown);
}
});
$('input, select').keydown(function(event) {
if (event.keyCode==16) {
shiftDown = true;
$('#shiftCatch').val(shiftDown);
}
if (event.keyCode==13) {
$('#captured').val(event.target.id);
} else if (event.keyCode==9 && shiftDown==false) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var nextEl = fields.eq(index+1).attr('id');
var firstEl = fields.eq(0).attr('id');
var focusEl = '#'+firstEl;
if (index>-1 && (index+1)<fields.length) {
$('#captured').val(nextEl);
} else if(index+1>=fields.length) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(firstEl);
} else {
event.preventDefault();
$(focusEl).focus();
}
}
return false;
});
} else if (event.keyCode==9 && shiftDown==true) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var prevEl = fields.eq(index-1).attr('id');
var lastEl = fields.eq(fields.length-1).attr('id');
var focusEl = '#'+lastEl;
if (index<fields.length && (index-1)>-1) {
$('#captured').val(prevEl);
} else if (index==0) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(lastEl);
} else {
event.preventDefault();
$(focusEl).select();
}
}
return false;
});
}
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 100 );
}
}
Edit #1: I made a few minor changes to the code, which has brought me a little closer to my intended functionality of the script. However, I only made one change to the code pertaining to the focus: I tried to to disable the tab keydown when pressed on the last element (and also the shift+tab keydown on the first element) in an attempt to force the focus on the element I want without skipping over it like it has been doing. This is the code I added:
$(this).one('keydown', function (event) {
return !(event.keyCode==9 && shiftDown==true);
});
This kind of works. After the page loads, If the user presses tab on the last element without making a change to its value, the focus will be set to the second element. However, the second time the user presses tab on the last element without making a change to its value, and every subsequent time thereafter, the focus will be set to the first element, just as I would like it to.
Edit #2: I replaced the code in Edit #1, with code utilizing event.preventDefault(), which works better. While if a user does a shift+tab keydown when in the first element, the focus moves to the last element as it should. However, if the user continues to hold down the shift key and presses tab again, focus will be set back to the first element. And if the user continues to hold the shift key down still yet and hits tab, the focus will move back to the last element. The focus will shift back and forth between the first and last element until the user lifts the shift key. This problem does not occur when only pressing tab. Here is the new code snippet:
event.preventDefault();
$(focusEl).focus();
You have a lot of code I didn't get full overview over, so I don't know if I missed some functionality you wanted integrated, but for the tabbing/shift-tabbing through form elements, this should do the work:
var elements = $("#container :input:visible");
var n = elements.length;
elements
.keydown(function(event){
if (event.keyCode == 9) { //if tab
var currentIndex = elements.index(this);
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
if (el.attr("type") == "text")
elements.eq(newIndex).select();
else
elements.eq(newIndex).focus();
event.preventDefault();
}
});
elements will be the jQuery object containing all the input fields, in my example it's all the input fields inside the div #container
Here's a demo: http://jsfiddle.net/rA3L9/
Here is the solution, which I couldn't have reached it without Simen's help. Thanks again, Simen.
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
$('#calculator :input:visible').each(function (i) {
$(this).data('initial', $(this).val());
});
return $(event.target).each(function() {
$('#c_main :input:visible').live(($.browser.opera ? 'keypress' : 'keydown'), function(event){
var elements = $("#calculator :input:visible");
var n = elements.length;
var currentIndex = elements.index(this);
if (event.keyCode == 13) { //if enter
var focusElement = elements.eq(currentIndex).attr('id');
$('#captured').val(focusElement);
} else if (event.keyCode == 9) { //if tab
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
var focusElement = el.attr('id');
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(focusElement);
} else if ((currentIndex==0 && event.shiftKey) || (currentIndex==n-1 && !event.shiftKey)) {
event.preventDefault();
if (el.attr('type')=='text') {
$.browser.msie ? "" : $(window).scrollTop(5000);
el.select().delay(800);
} else {
$.browser.msie ? "" : $(window).scrollTop(-5000);
el.focus().delay(800);
}
} else if (el.is('select')) {
event.preventDefault();
if (el.attr('type')=='text') {
el.select();
} else {
el.focus();
}
}
}
});
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 1 );
}
}
I put my files available to download in my live link: http://www.presspound.org/calculator/ajax/sample.php

Categories

Resources