Javascript Combo Box

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • harvey1492
    New Member
    • Oct 2007
    • 4

    #1

    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
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Use onkeypress (link) and the keycode to check for is 13 for the enter key.

    Comment

    • harvey1492
      New Member
      • Oct 2007
      • 4

      #3
      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

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        I think a 'return false' should be fine.

        If that doesn't work, post your code.

        Comment

        • harvey1492
          New Member
          • Oct 2007
          • 4

          #5
          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

          Code:
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          
          <html>
          <head>
          	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
          	<title>JavaScript ComboBox Example</title>
          	<style type="text/css">
          	body {
          		font-family : Verdana, Geneva, Arial, Helvetica, sans-serif;
          		font-size : 9px;
          	}
          	.comboLstTable {
          		font-size : 11px;
          		width : 94px;
          	}
          	.comboBox {
          		background-color : White;
          	}
          	.comboLstDiv {
          		overflow : auto;
          		position: absolute;
          		height:90px;
          		width:100px;
          		text-align : left;
          		padding : 2px 2px 2px 2px;
          		border-width : 1px 1px 1px 1px;
          		border-style : solid;
          		background-color : white;
          		display : none ;
          	}
          	.comboLstOut {
          		width : 100px;
          		background-color : white;
          		color : black ;
          	}
          	.comboLstOv {
          		width : 100px;
          		background-color : navy ;
          		color : white ;
          	}
          	.comboBtn {
          		width : 22px;
          		background-image: url(DnArrowUp.gif);
          	}
          	.comboBtnDn {
          		width : 22px;
          		background-image: url(DnArrowDn.gif);
          	}
          </style>
          <script language="JavaScript" type="text/javascript">
          
          // define global value of who is in focus
          var cInFocus = ''
          function setFocus(oControl) {
          	if (oControl.id != cInFocus) {
          	// clear old focus
          	    oOldControl = document.getElementById(cInFocus) ;
          	    if (oOldControl) BlurControl(oOldControl) ;
          	}
          	// update global var
          	cInFocus = oControl.id ;
          	oFeedBack=document.getElementById('FeedBack'); 
          	oFeedBack.innerHTML='' ;
          }
          
          // handle blur requirements
          function BlurControl(oControl) {
          	// include code here to handle blur of special controls
          	if (oControl.id.substr(0,5) == 'combo') comboBlur() ;
          }
          
          
          // init global values
          var nKeyDown = 0 
          var nKeyPress = 0
          var nAscii = 0  // stores the result we are looking for
          var lCtrl = false
          function KeyStroke(e) { // keyboard event fired
          
          	// get the key stroke event with browser compatibility
          	if (!e) var e = window.event ;
          	if (e.keyCode) code = e.keyCode;
          	else if (e.which) code = e.charCode;
          
          	//oFeedBack=document.getElementById('FeedBack');
          	//oFeedBack.innerHTML=code +' event.type = ' + e.type ;
          	//alert(e.type);
          	// keydown first to fire
            	if (e.type=='keydown') {
          		nKeyDown  = code
          		nKeyPress = 0
          		nAscii = code
          		lCtrl = true ;		
          	}
          
          	// keypress repeat fires when key held down
          	if (e.type=='keypress') { 
          		nKeyPress = code
          		//oFeedBack=document.getElementById('FeedBack');
          		//oFeedBack.innerHTML=nKeyPress ;
          		// key board scan codes and ascii key code overlap 
          		// if not shift-key pressed in keydown, assume control key pressed if code = cursor-key
          		if (nKeyDown!=57 && ( code>=33 && code<=40 || code==8 || code==9 || code==13)) {
          			nAscii = code ; 
          			lCtrl = true ;
          			//if (code==13) { e.cancelBubble };
          		}
          		else {
          		    lCtrl = false ;
          			nAscii = nKeyPress ;
          			//oFeedBack=document.getElementById('FeedBack');
          			//oFeedBack.innerHTML=nAscii ;
          		}
          	}
          	
          	if (e.type=='keyup') {
          		// ie does not fire keypress so to return ctrl must test from keyup
          		if (lCtrl) {
          		nAscii = nAscii * -1 ;
          		}
          		//oFeedBack=document.getElementById('FeedBack');
          		//oFeedBack.innerHTML=nAscii ;
          	}
          	//oFeedBack=document.getElementById('FeedBack');
          	//oFeedBack.innerHTML=e.type +' '+ nAscii + ' ' + lCtrl //String.fromCharCode(nAscii) ;
          	return true;
           }
          
          // global varibles that bind comboxBox controls
          var gComboBoxId, gComboTxtId, gComboBtnId, gComboLstId, gComboLstDivId
          // build the dropdown list values from an array
          var gaDropDownList = new Array()
          
          function initComboBox(comboBoxId,comboTxtId,comboBtnId,comboLstId,comboLstDivId) {
          	// setup relations between controls when control receives focus
          	gComboBoxId = comboBoxId ;
          	gComboTxtId = comboTxtId ;
          	gComboBtnId = comboBtnId ;
          	gComboLstId = comboLstId ;
          	gComboLstDivId = comboLstDivId ;
          
          	// populate the control with array properties
          	if (document.getElementById(gComboLstDivId) == null) {
          		gaDropDownList[0] = ''
          		gaDropDownList[1] = 'one'
          		gaDropDownList[2] = 'two'
          		gaDropDownList[3] = 'three'
          		gaDropDownList[4] = 'four'
          		gaDropDownList[5] = 'five'
          		gaDropDownList[6] = 'six'
          		// alert(gaDropDownList) ;
          		comboBoxLoad();
          	}
          }
          
          function comboBoxLoad() {
              // get reference to comboBox
          	oComboBox = document.getElementById(gComboBoxId)
          
          	// create the container for the dropdown list
          	oComboLstDiv = document.createElement('div');
          	oComboLstDiv.setAttribute('id',gComboLstDivId);
          	// set class properties
          	oComboLstDiv.className = 'comboLstDiv'
             // generate the options for the dropdown list
          	lcDiv = '<table class="comboLstTable" id="comboLst" border="0" cellspacing="0" cellpadding="0" onKeyPress="onValidKey(this)">'
          	for (i=0;i<gaDropDownList.length;++i) {
          		lcRow = '<tr>' ;
          		lcRow = lcRow + '<td id="comboLstCel' + i  + '"' ;
          		lcRow = lcRow + 'class="comboLstOut" onClick="optionClick(this)" onMouseOver="this.className=' + "'comboLstOv'" 
          		lcRow = lcRow + '"  onMouseOut=' + '"this.className=' + "'comboLstOut'" + '">' + gaDropDownList[i] + '</td></tr>'
          		lcDiv = lcDiv + lcRow
          	}
          	lcDiv = lcDiv + '</table>'
              // add the droplist to the page
          	oComboLstDiv.innerHTML=lcDiv ;	
          	oComboBox.appendChild(oComboLstDiv) ;
          }
          
          function comboBlur() {
          	// combo list must be colapsed alert('comboBlur') ;
          	oComboLstDiv = document.getElementById(gComboLstDivId) ;
          	oComboLstDiv.style.display='none' ;
          }
          
          function optionClick(oOption) {
          // move the list option into the text box and hide the list //alert(oOption.innerHTML);
          oComboLstDiv = document.getElementById(gComboLstDivId) ;
          oComboLstDiv.style.display='none' ;
          oComboTxt = document.getElementById(gComboTxtId) ;
          oComboTxt.value = oOption.innerHTML ;
          clearOptionLst() ;
          }
          
          function getOptionLst() {
          	// display option list, occurs when comboBox Dn Arrow is clicked or matching test is typed
          	oComboLstDiv = document.getElementById(gComboLstDivId) ;
          	if (oComboLstDiv.style.display == 'inline') {
          		oComboLstDiv.style.display='none' ;
          		}
          	else {
          		oComboLstBox = document.getElementById(gComboLstId) ;
          		// set the dropdown list height, assume font height set by class above
          		
               	// oComboLstDiv.style.setAttribute('height',(oComboLstBox.rows.length*12))
          		oComboLstDiv.style.display='inline' ;
          		oComboLstDiv.focus ;
          	}
          }
          
          function clearOptionLst() {
          	oComboLstBox = document.getElementById(gComboLstId) ;
          	for (k=0; k<oComboLstBox.rows.length; ++k) {
          		oComboLstBox.getElementsByTagName('TD')[k].className = 'comboLstOut' ;
          	}
          }
          
          function comboKeyStroke(oComboTxtBox) {
           	oComboLstBox = document.getElementById(gComboLstId) ; //init already fired so global naming is set
          
          	//oFeedBack=document.getElementById('FeedBack'); 
          	//oFeedBack.innerHTML=nAscii+'zz'
          
          	// handle cursor movement, is the list exposed
          	if (lCtrl) {
          	
          		nActive = 0 ;
          		for (jj=1; jj<oComboLstBox.rows.length;++jj) {
          			if (oComboLstBox.getElementsByTagName('TD')[jj].className == 'comboLstOv' ) { nActive = jj ; }
          		}
          
          		switch (nAscii)	{
          		 case -13 : // enter
          			if (nActive!=0) {
          				optionClick( document.getElementById('comboLstCel'+nActive) ) ;
          				// if user changes their mind...active must not be selected 
          				oComboLstBox.getElementsByTagName('TD')[nActive].className = 'comboLstOut' ;
          			}
          			break ;			
          		 case -38 : // up arrow
          		 	if (nActive!=0) {
          				// remove highlighting from active line
          				oComboLstBox.getElementsByTagName('TD')[nActive].className = 'comboLstOut' ;
          				// highlight new line
          				oComboLstBox.getElementsByTagName('TD')[nActive-1].className = 'comboLstOv' ;
          			}
          		 break ;
          		 case -40 : // dn arrow
          			// be sure to display the list
          			if (nActive==0) {
          				getOptionLst() ;
          			}
          		 	if (nActive<oComboLstBox.rows.length-1) {
          				// remove highlighting from active line
          				oComboLstBox.getElementsByTagName('TD')[nActive].className = 'comboLstOut' ;
          				// highlight new line
          				oComboLstBox.getElementsByTagName('TD')[nActive+1].className = 'comboLstOv' ;
          			}
          		 break ;
          		 } //end switch
          	    oComboTxtBox.focus() ;
          		return ;
          	}
          	
          	// lookup select list for closest match
          	for (i=0; i<=oComboTxtBox.value.length ; ++i) {
          		for (j=1; j<oComboLstBox.rows.length; ++j) {
          	    	// current keystroke is not yet in the testbox
          			// +1 includes the current keystroke in length comparison
          			//if (oComboTxtBox.value.length +1 > oComboLstBox.getElementsByTagName('TD')[j].innerHTML.length) { alert('break length'); break; }
          			if (oComboLstBox.getElementsByTagName('TD')[j].innerHTML.substr(0,i+1)==oComboTxtBox.value.substr(0,i) + String.fromCharCode(nAscii) ) {
          			
          				clearOptionLst() ; // first clear an old selection
          			 	// set the select option as selected and exit
          	  		 	oComboLstBox.getElementsByTagName('TD')[j].className = 'comboLstOv' ; 
          				//ensure the list is displayed with selected option
          				
          				oComboLstDiv = document.getElementById('comboLstDiv') ;
          				
          				oComboLstDiv.style.display='inline';
          			  break ;
          			 }
          		} // end for j
          		// alert(oComboTxtBox.value.substr(i,1)) ;
          	} //end for i
          	oComboTxtBox.focus() ;
          } //end comboKeyUp()
          
          //var lSubmit = false ;
          function submitWhen(lSubmit) {
          //alert(lSubmit);
          //if (lSubmit=='click') this.returnValue = false ;
          //if (lSubmit!=true) return false ;
          oFeedBack=document.getElementById('FeedBack'); 
          oFeedBack.innerHTML='submit fired' ;
          return true ;
          }
          
          // -->
          </script>
          
          </head>
          <body>
          <form action="helloworld.htm" onsubmit="return submitWhen();">
          <div id="comboBox" class="comboBox"><table width="20" border="0" cellspacing="0" cellpadding="0">
          	<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>
          	<tr>
          		<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>
          		<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>
          	</tr>
          	</table>
          </div>
          	<input type="submit" onclick="submitWhen('click');">
          
          </form>
          <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
          
          
          <br><br>
          oFeedBack=document.getElementById('FeedBack'); <br>
          oFeedBack.innerHTML=cInFocus <br><br>
          
          <span id='FeedBack'></span>
          
          
          </body>
          </html>

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            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="hellowo rld.htm" onsubmit="retur n false;">
            <input type="button" onclick="this.f orm.submit();">[/HTML]

            Comment

            Working...