473,322 Members | 1,408 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Javascript Combo Box

I have created a combo box in javascript that I plan to include on a data entry screen.

I'm having a problem preventing the form submit from firing when the Enter key is pressed on a selection. I would like to trap the default handling, test to see if the submit button was pressed and if not cancel the event.

Thanks in advance, Harvey
Oct 22 '07 #1
5 7706
acoder
16,027 Expert Mod 8TB
Use onkeypress (link) and the keycode to check for is 13 for the enter key.
Oct 22 '07 #2
I already trap the onKeyDown, onKeyPress and onKeyUp which makes the control I've created compatible on IE and Firefox.

Now I need to understand how to cancel the event once the key is pressed.

preventDefault
stopPropagation
returnValue = false
cancelBubble = true

All of these properties seem to play into the event tree but it is not clear to me which are needed in this case and when to include them in my code - on the event of a key being pressed on when the form wants to submit.

--hm
Oct 22 '07 #3
acoder
16,027 Expert Mod 8TB
I think a 'return false' should be fine.

If that doesn't work, post your code.
Oct 22 '07 #4
My sample code is below. Down around line 294 I have a feed back routine that should only fire when the submit button is pressed.

At this point with your cursor in the textbox, if you press the down arrow key, the select list will be exposed. Then press the Enter key to select the highlighted item. At this point, after the item is selected, I need to cancel the bubbling of the Submit event which automaticlly fired.

--Harvey

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2.  
  3. <html>
  4. <head>
  5.     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
  6.     <title>JavaScript ComboBox Example</title>
  7.     <style type="text/css">
  8.     body {
  9.         font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
  10.         font-size : 9px;
  11.     }
  12.     .comboLstTable {
  13.         font-size : 11px;
  14.         width : 94px;
  15.     }
  16.     .comboBox {
  17.         background-color : White;
  18.     }
  19.     .comboLstDiv {
  20.         overflow : auto;
  21.         position: absolute;
  22.         height:90px;
  23.         width:100px;
  24.         text-align : left;
  25.         padding : 2px 2px 2px 2px;
  26.         border-width : 1px 1px 1px 1px;
  27.         border-style : solid;
  28.         background-color : white;
  29.         display : none ;
  30.     }
  31.     .comboLstOut {
  32.         width : 100px;
  33.         background-color : white;
  34.         color : black ;
  35.     }
  36.     .comboLstOv {
  37.         width : 100px;
  38.         background-color : navy ;
  39.         color : white ;
  40.     }
  41.     .comboBtn {
  42.         width : 22px;
  43.         background-image: url(DnArrowUp.gif);
  44.     }
  45.     .comboBtnDn {
  46.         width : 22px;
  47.         background-image: url(DnArrowDn.gif);
  48.     }
  49. </style>
  50. <script language="JavaScript" type="text/javascript">
  51.  
  52. // define global value of who is in focus
  53. var cInFocus = ''
  54. function setFocus(oControl) {
  55.     if (oControl.id != cInFocus) {
  56.     // clear old focus
  57.         oOldControl = document.getElementById(cInFocus) ;
  58.         if (oOldControl) BlurControl(oOldControl) ;
  59.     }
  60.     // update global var
  61.     cInFocus = oControl.id ;
  62.     oFeedBack=document.getElementById('FeedBack'); 
  63.     oFeedBack.innerHTML='' ;
  64. }
  65.  
  66. // handle blur requirements
  67. function BlurControl(oControl) {
  68.     // include code here to handle blur of special controls
  69.     if (oControl.id.substr(0,5) == 'combo') comboBlur() ;
  70. }
  71.  
  72.  
  73. // init global values
  74. var nKeyDown = 0 
  75. var nKeyPress = 0
  76. var nAscii = 0  // stores the result we are looking for
  77. var lCtrl = false
  78. function KeyStroke(e) { // keyboard event fired
  79.  
  80.     // get the key stroke event with browser compatibility
  81.     if (!e) var e = window.event ;
  82.     if (e.keyCode) code = e.keyCode;
  83.     else if (e.which) code = e.charCode;
  84.  
  85.     //oFeedBack=document.getElementById('FeedBack');
  86.     //oFeedBack.innerHTML=code +' event.type = ' + e.type ;
  87.     //alert(e.type);
  88.     // keydown first to fire
  89.       if (e.type=='keydown') {
  90.         nKeyDown  = code
  91.         nKeyPress = 0
  92.         nAscii = code
  93.         lCtrl = true ;        
  94.     }
  95.  
  96.     // keypress repeat fires when key held down
  97.     if (e.type=='keypress') { 
  98.         nKeyPress = code
  99.         //oFeedBack=document.getElementById('FeedBack');
  100.         //oFeedBack.innerHTML=nKeyPress ;
  101.         // key board scan codes and ascii key code overlap 
  102.         // if not shift-key pressed in keydown, assume control key pressed if code = cursor-key
  103.         if (nKeyDown!=57 && ( code>=33 && code<=40 || code==8 || code==9 || code==13)) {
  104.             nAscii = code ; 
  105.             lCtrl = true ;
  106.             //if (code==13) { e.cancelBubble };
  107.         }
  108.         else {
  109.             lCtrl = false ;
  110.             nAscii = nKeyPress ;
  111.             //oFeedBack=document.getElementById('FeedBack');
  112.             //oFeedBack.innerHTML=nAscii ;
  113.         }
  114.     }
  115.  
  116.     if (e.type=='keyup') {
  117.         // ie does not fire keypress so to return ctrl must test from keyup
  118.         if (lCtrl) {
  119.         nAscii = nAscii * -1 ;
  120.         }
  121.         //oFeedBack=document.getElementById('FeedBack');
  122.         //oFeedBack.innerHTML=nAscii ;
  123.     }
  124.     //oFeedBack=document.getElementById('FeedBack');
  125.     //oFeedBack.innerHTML=e.type +' '+ nAscii + ' ' + lCtrl //String.fromCharCode(nAscii) ;
  126.     return true;
  127.  }
  128.  
  129. // global varibles that bind comboxBox controls
  130. var gComboBoxId, gComboTxtId, gComboBtnId, gComboLstId, gComboLstDivId
  131. // build the dropdown list values from an array
  132. var gaDropDownList = new Array()
  133.  
  134. function initComboBox(comboBoxId,comboTxtId,comboBtnId,comboLstId,comboLstDivId) {
  135.     // setup relations between controls when control receives focus
  136.     gComboBoxId = comboBoxId ;
  137.     gComboTxtId = comboTxtId ;
  138.     gComboBtnId = comboBtnId ;
  139.     gComboLstId = comboLstId ;
  140.     gComboLstDivId = comboLstDivId ;
  141.  
  142.     // populate the control with array properties
  143.     if (document.getElementById(gComboLstDivId) == null) {
  144.         gaDropDownList[0] = ''
  145.         gaDropDownList[1] = 'one'
  146.         gaDropDownList[2] = 'two'
  147.         gaDropDownList[3] = 'three'
  148.         gaDropDownList[4] = 'four'
  149.         gaDropDownList[5] = 'five'
  150.         gaDropDownList[6] = 'six'
  151.         // alert(gaDropDownList) ;
  152.         comboBoxLoad();
  153.     }
  154. }
  155.  
  156. function comboBoxLoad() {
  157.     // get reference to comboBox
  158.     oComboBox = document.getElementById(gComboBoxId)
  159.  
  160.     // create the container for the dropdown list
  161.     oComboLstDiv = document.createElement('div');
  162.     oComboLstDiv.setAttribute('id',gComboLstDivId);
  163.     // set class properties
  164.     oComboLstDiv.className = 'comboLstDiv'
  165.    // generate the options for the dropdown list
  166.     lcDiv = '<table class="comboLstTable" id="comboLst" border="0" cellspacing="0" cellpadding="0" onKeyPress="onValidKey(this)">'
  167.     for (i=0;i<gaDropDownList.length;++i) {
  168.         lcRow = '<tr>' ;
  169.         lcRow = lcRow + '<td id="comboLstCel' + i  + '"' ;
  170.         lcRow = lcRow + 'class="comboLstOut" onClick="optionClick(this)" onMouseOver="this.className=' + "'comboLstOv'" 
  171.         lcRow = lcRow + '"  onMouseOut=' + '"this.className=' + "'comboLstOut'" + '">' + gaDropDownList[i] + '</td></tr>'
  172.         lcDiv = lcDiv + lcRow
  173.     }
  174.     lcDiv = lcDiv + '</table>'
  175.     // add the droplist to the page
  176.     oComboLstDiv.innerHTML=lcDiv ;    
  177.     oComboBox.appendChild(oComboLstDiv) ;
  178. }
  179.  
  180. function comboBlur() {
  181.     // combo list must be colapsed alert('comboBlur') ;
  182.     oComboLstDiv = document.getElementById(gComboLstDivId) ;
  183.     oComboLstDiv.style.display='none' ;
  184. }
  185.  
  186. function optionClick(oOption) {
  187. // move the list option into the text box and hide the list //alert(oOption.innerHTML);
  188. oComboLstDiv = document.getElementById(gComboLstDivId) ;
  189. oComboLstDiv.style.display='none' ;
  190. oComboTxt = document.getElementById(gComboTxtId) ;
  191. oComboTxt.value = oOption.innerHTML ;
  192. clearOptionLst() ;
  193. }
  194.  
  195. function getOptionLst() {
  196.     // display option list, occurs when comboBox Dn Arrow is clicked or matching test is typed
  197.     oComboLstDiv = document.getElementById(gComboLstDivId) ;
  198.     if (oComboLstDiv.style.display == 'inline') {
  199.         oComboLstDiv.style.display='none' ;
  200.         }
  201.     else {
  202.         oComboLstBox = document.getElementById(gComboLstId) ;
  203.         // set the dropdown list height, assume font height set by class above
  204.  
  205.          // oComboLstDiv.style.setAttribute('height',(oComboLstBox.rows.length*12))
  206.         oComboLstDiv.style.display='inline' ;
  207.         oComboLstDiv.focus ;
  208.     }
  209. }
  210.  
  211. function clearOptionLst() {
  212.     oComboLstBox = document.getElementById(gComboLstId) ;
  213.     for (k=0; k<oComboLstBox.rows.length; ++k) {
  214.         oComboLstBox.getElementsByTagName('TD')[k].className = 'comboLstOut' ;
  215.     }
  216. }
  217.  
  218. function comboKeyStroke(oComboTxtBox) {
  219.      oComboLstBox = document.getElementById(gComboLstId) ; //init already fired so global naming is set
  220.  
  221.     //oFeedBack=document.getElementById('FeedBack'); 
  222.     //oFeedBack.innerHTML=nAscii+'zz'
  223.  
  224.     // handle cursor movement, is the list exposed
  225.     if (lCtrl) {
  226.  
  227.         nActive = 0 ;
  228.         for (jj=1; jj<oComboLstBox.rows.length;++jj) {
  229.             if (oComboLstBox.getElementsByTagName('TD')[jj].className == 'comboLstOv' ) { nActive = jj ; }
  230.         }
  231.  
  232.         switch (nAscii)    {
  233.          case -13 : // enter
  234.             if (nActive!=0) {
  235.                 optionClick( document.getElementById('comboLstCel'+nActive) ) ;
  236.                 // if user changes their mind...active must not be selected 
  237.                 oComboLstBox.getElementsByTagName('TD')[nActive].className = 'comboLstOut' ;
  238.             }
  239.             break ;            
  240.          case -38 : // up arrow
  241.              if (nActive!=0) {
  242.                 // remove highlighting from active line
  243.                 oComboLstBox.getElementsByTagName('TD')[nActive].className = 'comboLstOut' ;
  244.                 // highlight new line
  245.                 oComboLstBox.getElementsByTagName('TD')[nActive-1].className = 'comboLstOv' ;
  246.             }
  247.          break ;
  248.          case -40 : // dn arrow
  249.             // be sure to display the list
  250.             if (nActive==0) {
  251.                 getOptionLst() ;
  252.             }
  253.              if (nActive<oComboLstBox.rows.length-1) {
  254.                 // remove highlighting from active line
  255.                 oComboLstBox.getElementsByTagName('TD')[nActive].className = 'comboLstOut' ;
  256.                 // highlight new line
  257.                 oComboLstBox.getElementsByTagName('TD')[nActive+1].className = 'comboLstOv' ;
  258.             }
  259.          break ;
  260.          } //end switch
  261.         oComboTxtBox.focus() ;
  262.         return ;
  263.     }
  264.  
  265.     // lookup select list for closest match
  266.     for (i=0; i<=oComboTxtBox.value.length ; ++i) {
  267.         for (j=1; j<oComboLstBox.rows.length; ++j) {
  268.             // current keystroke is not yet in the testbox
  269.             // +1 includes the current keystroke in length comparison
  270.             //if (oComboTxtBox.value.length +1 > oComboLstBox.getElementsByTagName('TD')[j].innerHTML.length) { alert('break length'); break; }
  271.             if (oComboLstBox.getElementsByTagName('TD')[j].innerHTML.substr(0,i+1)==oComboTxtBox.value.substr(0,i) + String.fromCharCode(nAscii) ) {
  272.  
  273.                 clearOptionLst() ; // first clear an old selection
  274.                  // set the select option as selected and exit
  275.                    oComboLstBox.getElementsByTagName('TD')[j].className = 'comboLstOv' ; 
  276.                 //ensure the list is displayed with selected option
  277.  
  278.                 oComboLstDiv = document.getElementById('comboLstDiv') ;
  279.  
  280.                 oComboLstDiv.style.display='inline';
  281.               break ;
  282.              }
  283.         } // end for j
  284.         // alert(oComboTxtBox.value.substr(i,1)) ;
  285.     } //end for i
  286.     oComboTxtBox.focus() ;
  287. } //end comboKeyUp()
  288.  
  289. //var lSubmit = false ;
  290. function submitWhen(lSubmit) {
  291. //alert(lSubmit);
  292. //if (lSubmit=='click') this.returnValue = false ;
  293. //if (lSubmit!=true) return false ;
  294. oFeedBack=document.getElementById('FeedBack'); 
  295. oFeedBack.innerHTML='submit fired' ;
  296. return true ;
  297. }
  298.  
  299. // -->
  300. </script>
  301.  
  302. </head>
  303. <body>
  304. <form action="helloworld.htm" onsubmit="return submitWhen();">
  305. <div id="comboBox" class="comboBox"><table width="20" border="0" cellspacing="0" cellpadding="0">
  306.     <tr><td><img src="spacer.gif" width="1" height="1" border="0" alt=""></td><td><img src="spacer.gif" width="50" height="1" border="0" alt=""></td></tr>
  307.     <tr>
  308.         <td><input id="comboTxt" onkeydown="KeyStroke(event)" onkeypress="KeyStroke(event)" onkeyup="KeyStroke(event); comboKeyStroke(this)" onfocus="setFocus(this); initComboBox('comboBox','comboTxt','comboBtn','comboLst','comboLstDiv')" type="text" style="width:82px;" maxlength="20" ></td>
  309.         <td><input width="20" type="button" class="comboBtn" id="comboBtn" onMouseDown="this.className='comboBtnDn'" onMouseUp="this.className='comboBtn'" onClick="setFocus(this); initComboBox('comboBox','comboTxt','comboBtn','comboLst','comboLstDiv'); getOptionLst(this);"></td>
  310.     </tr>
  311.     </table>
  312. </div>
  313.     <input type="submit" onclick="submitWhen('click');">
  314.  
  315. </form>
  316. <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  317.  
  318.  
  319. <br><br>
  320. oFeedBack=document.getElementById('FeedBack'); <br>
  321. oFeedBack.innerHTML=cInFocus <br><br>
  322.  
  323. <span id='FeedBack'></span>
  324.  
  325.  
  326. </body>
  327. </html>
  328.  
  329.  
Oct 22 '07 #5
acoder
16,027 Expert Mod 8TB
The following simple solution seems to work, but it does have one big problem: there's no submit button, so the page will only work with JavaScript enabled.
[HTML]<form action="helloworld.htm" onsubmit="return false;">
<input type="button" onclick="this.form.submit();">[/HTML]
Oct 23 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Matt | last post by:
The ASP page has a combo box with id list, and when user click the particular id, it will show the name in the text box. My attempt was when the user have event on combo box, it will call...
8
by: rikesh | last post by:
Hi I'm sure this is a very trivial problem! I have a combo bound to a recordset. I was wondering how I can show the value on the page, what the user has selected? The code that I'm using is...
13
by: mr_burns | last post by:
hi, is it possible to change the contents of a combo box when the contents of another are changed. for example, if i had a combo box called garments containing shirts, trousers and hats, when...
2
by: kiranmn75 | last post by:
I want to dynamically populate a combo box through javascript. Data is coming from a array. Sometimes data list may contain items in excess of 2000. Explorer takes more than 5 seconds to...
0
by: Cndla | last post by:
hi, I have two combo boxes in a form. Functionality is such that selecting a value from the first combo box changes the value in the second combo box. Now this works fine in a normal computer with...
1
by: The Eclectic Electric | last post by:
I'd be very grateful if anyone could help me with this. From my limited knowledge of Javascript I don't think it is possible, but I'll punt anyway. I downloaded and very slightly adapted this...
1
by: kuttans | last post by:
The following is the code i used to load a combo using javascript xmlDoc=document.implementation.createDocument("","",null); xmlDoc.async="false";xmlDoc.preserveWhiteSpace=true;...
2
by: someshbakliwal | last post by:
Hi, I have created some autopopulating combo boxes on my HTML page (script- Javascript). so these combo boxes are autopopulated with choices made in previous combo boxes. The problem I am facing is...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.