Adding JavaScript/Jquery code in InfoPath forms
Some times you may face requirement to access controls of InfoPath form in javascript. Then below approaches may helpful.
Example requirement: Client asks you to handle enter key to navigate from one control to another control on the form or execute rules when user enters a value in a text box and hits enter. Usually, in infopath form, we use Tab key instead Enter key for such requirements.
To fulfill such requirements, we have to go with JavaScript code that will read the enter key number (13) and then you will make that as Tab key(if i am not wrong, i guess it is 8).
There are two ways in adding JavaScript for InfoPath forms.
Method 1) in code behind of InfoPath form
Method 2) in FormServer.aspx page in layouts folder
Method 1 will effect the script funcionality only on your form. where as method 2 will effect for all forms. because InfoPath forms will load as control on FormServer.aspx page.
In Method 2 also, you have to use delay() method in javascript before reading the controls. Because, generally the script will execute before the control i.e., form loads. writing delay(1000) will help the script wait for 1 second and in this time, the form will load and so you can read the controls based on your requirement.
For method 1, you need to write in the code as shown in below example:
//This is to handle back space key press.
//page should not go back when user clicks backspace key. It will work as usuall when cursor is in any control
HttpContext.Current.Response.Write("<script type='text/javascript'>" +
"if (typeof window.event != 'undefined')" +
"{document.onkeydown = function(){" +
"if (event.srcElement.tagName.toUpperCase() != 'INPUT')return (event.keyCode != 8);}}" +
"else{document.onkeypress = function(e){if (e.target.nodeName.toUpperCase() != 'INPUT')return (e.keyCode != 8);}" +
"}</script>");
happy coding :)