CChoma CChoma - 2 months ago 13
Javascript Question

jQuery .change only works for first instance

I've got a series of conditional select elements that uses

.load
to insert dynamic content from an external file. The problem is it fires for the first element only and any subsequent instances result in no action.

I started off with this:

jQuery(document).ready(function($) {


$('#autocad-level-1').change(function() {

var cat_id = $(this).val();
console.log('Category Selected');
$('#autocad-level-2-container').load('http://website.dev/wp-content/themes/dmi/ajax/autocad-level-2.php?cat_id='+cat_id);

});

$('#autocad-level-2').change(function() {

var p_id = $(this).val();
console.log('Product Selected');
$('#autocad-level-3-container').load('http://website.dev/wp-content/themes/dmi/ajax/autocad-level-3.php?p_id='+p_id);

});

});


Research suggested I should use
.on
as the event handler, but I had no success with that either.

jQuery(document).ready(function($) {

$('#autocad-level-1').on("change", "select", function() {

var cat_id = $(this).val();
console.log('Category Selected');
$('#autocad-level-2-container').load('http://website.dev/wp-content/themes/dmi/ajax/autocad-level-2.php?cat_id='+cat_id);

});

$('#autocad-level-2').on("change", "select", function() {

var p_id = $(this).val();
console.log('Product Selected');
$('#autocad-level-3-container').load('http://website.dev/wp-content/themes/dmi/ajax/autocad-level-3.php?p_id='+p_id);

});

});


This is my HTML:

<div id="autocad-level-1-container">
<select id="autocad-level-1" name="autocad-level-1">
<option value="0">Select</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
...
</select>
</div>
<div id="autocad-level-2-container"></div>
<div id="autocad-level-3-container"></div>


What am I doing wrong here? I'm out of ideas.

Answer

You need to listen to the select from a parent element, not the select itself.

$('#autocad-level-2-container').on("change", "#autocad-level-2", function() { 
    /*** code here ***/
});