views:

220

answers:

2

I am using HTML select onchange event to fire another javascript function func1.

This html select is written into a form element, which are dynamically generated when users click on a button.

The problem is how can I fire the javascript func1 when the dynamically generated form is first shown ? I am thinking of something along the line of on_first_show event for form ?

Here is the snippet. I couldnt get the alert('don') to work either (the one just after div)

var sPopupContents = "<div ><script type='text/javascript'>alert('don');</script> </div>"; // this javascript is not executed ? I cant get the alert.
sPopupContents += "<form name='theform' >";
sPopupContents += "<select name='theselect' onchange='alert(2);";
sPopupContents += "func1()>'";
sPopupContents += "<option value='0' selected='selected'>Value1</option><option value='1'>Value2</option><br/>";
sPopupContents += "</form>";

-- EDIT -- I guess I can add another option in the html select that tells users to select, so forcing the onchange to take effect. Or I can just add a Submit button.

+1  A: 

You could use document.createElement method instead of using literal srings, and add the onchange event handler by calling addEventListener.

You are closing the select tag before the single quote

sPopupContents += "<select name='theselect' onchange='alert(2);";
sPopupContents += "func1()>'";

should be:

sPopupContents += "<select name='theselect' onchange='alert(2);";
sPopupContents += "func1()'>";
Matias
A: 

A library such as jQuery would let you do this:

(function() {
  function selectChange() {
    // save baby seals here
  };

  $('select[name=theselect]').live('change', selectChange)
  $(document).ready(selectChange);
}();

You don't need a library for this for most browsers, however. A change event will bubble up to the containing element, so you can listen for it there. I believe it's IE that won't bubble up a change event.

wombleton