0

How to call a function when I click over an 'option' (HTML select > option) when that element is created in javascript and not exists in the html ? here I'm not using jquery or ajax, is just javascript

in my html I only have:

<fieldset>
    <legend>List...</legend>

    <select id="select1" size="9" style="width:150px">
        <option>Select a person</option>
    </select>
</fieldset>
  • more options (persons) are created in another function
vincent thorpe
  • 171
  • 1
  • 10
  • 4
    Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements).That should do you. – Robert Moskal Aug 14 '16 at 02:41
  • 1
    Just put a click handler on the select in which you test the select's current value - why do you need a click handler on the option itself as compared to wanting to know in a general sense when the select's current selection changes? Or 2. Bind a click handler to the option at the time it is created. Or 3. Use a delegated event handler bound to the select. – nnnnnn Aug 14 '16 at 02:54

1 Answers1

-1

Use the onchange event

Without using jquery

document.body.onchange = function(e) {
    if (e.target.tagName=='SELECT'){
        SelectedOption(e.target);
    }
}
function SelectedOption(option){
    alert(option.value);
    alert(option.id);
}

Another example from the select control

<select onchange="javascript:SelectedOption(event.target)" > ...