"onclick", "this", and popups

Discussion in 'General Webmaster Support' started by perkeyone, Jan 6, 2011.

  1. perkeyone

    perkeyone something clever

    Ratings:
    +71 / 0 / -0
    i am trying to make a web page which has a dynamic form.
    this form will have an "pop" button on it which will open a pop-up.
    in the pop up there will be a field for input and a "add" button.
    when the pop-up's "add" button is pressed, the original page will have a button added to it.
    clicking this new button will cause it to delete itself.

    i am trying to create the "self removing" button with javascript and i want to make sure the onclick event assignment is cross browser compatible.
    right now it works in ie and firefox, but not 100%... the functions currently only work so long as the popup remains open.

    also im expecting any changes i make to the code inorder to fix this problem will break the code.
    one thing i also want to be mindful of is what "this" refers to in the event that i am attaching to the button.

    i made 2 files specifically to debug this.
    the first is the page, and the second is the pop-up.
    Code:
    <html>
    	<head>
    		<script type="text/javascript">
    			function rem(){
    				alert("removing "+this.value);
    				this.parentNode.removeChild(this);}
    			function pop(){
    				win=window.open("popup.php","","scrollbars=yes,menubar=no,width=350,height=100,top=100,left=320,alwaysRaised=yes,location=0");
    				win.creator=self;
    				win.focus();}</script></head>
    	<body>
    		<form name="f" action="">
    			<input type="button" value="pop" onclick="pop()"/><br/></form></body></html>
    Code:
    <html>
    	<head>
    		<script type="text/javascript">
    			function rem(){
    				alert("removing"+this.value);
    				this.parentNode.removeChild(this);}
    			function add(){
    				var b=creator.document.createElement('input');
    				b.type='button';
    				b.value=document.p.t.value;
    				b.onclick=rem;
    				creator.document.f.appendChild(b);}</script></head>
    	<body>
    		<form name="p" action="">
    			<input name="t" type="text"/>
    			<input type="button" value="add" onclick="add()"/></form></body></html>
    also before anyone asks, i intentionally left out things like doctype to minimize code since it is strictly for debugging.
     
  2. perkeyone

    perkeyone something clever

    Ratings:
    +71 / 0 / -0
    wow. i figured it out after i noticed a small typo.
    both documents have a function called "rem" but one has a space in the alert message and the other does not.
    i realized that it was using the rem function from the pop-up, so when i close the pop-up it no longer had a reference to the function.
    so, instead of
    Code:
    b.onclick=rem
    i just use
    Code:
    b.onclick=creator.rem
     

Share This Page