SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2006
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problem with detachEvent from a selectbox

    HTML Code:
    <html>
    	<head>
    		<title>Testing</title>
    		<script type="text/javascript">
    		function yes(){
    			alert(document.getElementById('t1').options[document.getElementById('t1').selectedIndex].value);
    		}
    		
    		function addEvent( obj, type, fn ) {
    		  if ( obj.attachEvent ) {
    		    obj['e'+type+fn] = fn;
    		    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    		    obj.attachEvent( 'on'+type, obj[type+fn] );
    		  } else
    		    obj.addEventListener( type, fn, false );
    		}
    		function removeEvent( obj, type, fn ) {
    		  if ( obj.detachEvent ) {
    		    obj.detachEvent( 'on'+type, obj[type+fn] );
    		    obj[type+fn] = null;
    		  } else{
    		    obj.removeEventListener( type, fn, false );
    		  }
    		}
    		function yes2(){
    			alert('12');	
    		}
    		</script>
    		<script src="jquery.js" type="text/javascript"></script>
    	</head>
    	<body>
    		<form name="good" method="post" action="">
    		<select name="t1" id="t1" onchange="yes();">
    			<option value="1">1</option>
    			<option value="2">2</option>
    			<option value="3">3</option>
    		</select>
    		</form>
    	</body>
    	<script type="text/javascript">
    		removeEvent(document.getElementById('t1'), 'onchange', yes);
    	</script>
    </html>
    There will be a default onchange function for the selectbox, but for separate script, I need to onfly detach the event and re-attach a new function to it. But, it seems that not working at all. Anybody know what going on and what is the solution? Thanks

  2. #2
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You have to add the event in the same manner as you intend to remove it:

    Code JavaScript:
    addEvent(document.getElementById('t1'), 'onchange', yes);
    removeEvent(document.getElementById('t1'), 'onchange', yes);

    (remove 'onchange="yes();"' from the HTML)
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •