1

Using javascript, I have taken data from a JSON file and placed it into an HTML select element. Each item from the JSON file is in a different option element within the select.

I would like to now be able to display a user's selected option in an HTML input element. I thought that this would work using this code:

<script>
$( "select" )
  .change(function() {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $( this ).text() + " ";
    });
    $( "div" ).text( str );
  })
  .trigger( "change" );
</script>

I think my issue is that my HTML generated from the javascript is not recognized. Is there a way I can make this work?

Thanks

user3653771
  • 107
  • 5

1 Answers1

1

Yes, if you are generating your select dinamically, you need to do event delegation.

Change:

$( "select" ).change(...

To:

$(closestParent).on("change", "select", function()...

The "closestParent" is the closest element of the select which is not being generated dinamically (you can even use "body" and it will work)

Pietro Coelho
  • 1,894
  • 1
  • 26
  • 34