MrCycling
MrCycling

Reputation: 3004

Select changes not triggering if added by JQuery

I have a multi level select chain, where by the value of the first select generates the options for the next select list. And within the second list some of the values will cause a div to display with another input.

My codes (below) seem to work just fine when tested on static content (ie: the second select is hard coded in the html). But when I add it with JQuery, the second level no longer triggers the .change function.

<script type="text/javascript">
$(document).ready(function() {
  $dts = $("select[name='tourdes']");
  $dts.change(function() { 
     var dtsValue = $(this).val();
     var dtsString = '?tourdes=' + dtsValue; 
     $('#dateSelect').show();
     $('#dateSelect').load('include/avdates.php' + dtsString).append();
  });
});
</script>

<script type="text/javascript">
$(document).ready(function() {
  $tags = $("select[name='tourcode']");
  $tags.change(function() {
     if ($(this).val() == "private") {
     $(".prvcal").css({"visibility":"visible"});
  }
  });
});
</script>

I am guessing something needs to be re-initialized, but I am getting no where with my experiments.

Upvotes: 1

Views: 144

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83376

If you're using jQuery 1.7 you'll want to use on, as both live and delegate are deprecated.

$(document).on("change", "select[name='tourcode']", function() {
    var dtsValue = $(this).val();
    var dtsString = '?tourdes=' + dtsValue; 
    $('#dateSelect').show();
    $('#dateSelect').load('include/avdates.php' + dtsString).append();
});

docs for on()

Upvotes: 1

Blender
Blender

Reputation: 298582

You are probably using dynamically-generated HTML elements. If that is the case, you need to use .delegate() to handle them:

$('select').delegate("[name='tourdes']", 'change', function() { 

Upvotes: 1

Related Questions