0

I am trying to generate a dynamic dropdown on a mouse over event over an object. I accomplished it like so,

  canvas.on('mouse:move', function (e) {

      $('body').append("<div id='imageDialog' style='position: absolute; top: 0; left: 0'><select id='mySelect' onchange='copy();'><option value='wipro' >wipro</option><option value='Hcl' >Hcl</option><option value='krystal kones' >krystal kones</option></select></div>");

  });

This functionality works fine. But there is an issue in my next requirement where I need to capture the selected item when the user selectes an item from the drop down. I know its a long shot but I tried it by having onchange='copy();' in the drop down and alerting out the selection made like so,

function copy(){
    alert(document.getElementById("imageDialog").value);
}

But as expected it gave the error Uncaught ReferenceError: copy is not defined.

I was at this for some time and had no luck whatsoever and I would really appreciate any help from you experts regarding this.

Thanks.

2 Answers 2

2

I'm not sure I understand some of these design decisions (generating select boxes is an odd way to do a dropdown menu) but we'll skip that part for now and get to the good stuff.

When you add new elements to the DOM after initial load, you need to think of event binding a little differently. Since these initial elements weren't around when you first said "Hey, all elements do this when I hover on you", the way you handle it is by telling a parent element instead. Sticking in jQuery-land:

$('.parent-element').on('click', '.child-element', function (){ });

This gives you the same result as assigning click directly to .child-element if it was around at initial render. You can read more about delegated events here: http://api.jquery.com/on/

Here's a fiddle that cleans up your stuff a bit: http://jsfiddle.net/g6r8k6dk/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the advice. I will check on this post back :)
0

without using pure javascript, use jQuery like the following code.

$('document').ready(function(){
   $('#imageDialog').on('click',function(){
       alert($('#imageDialog select').value);
   })
})

2 Comments

Thanks alot for this :) i will check and post back
Hi the answer was not actually I expected. thanks alot for the help. the answer posted by Zach Dunn works for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.