William Cross William Cross - 4 months ago 9
jQuery Question

Why does this not want to find the selector on dynamic content?

I have the below select to choose a second form to pull in via

load()
into the
#formContent
div
which works fine.

<form id="selectform">
<select id="selector" class="form-control" name="selector">
<option value="" selected="selected">Choose your Poison</option>
<option value="website">Website</option>
</select>
</form>
<div id="formContent"> </div>


The form that gets pulled in is:

<form id="website">
<div class="control-group form-group">
<label for="name">Name:</label>
<input name="name" type="text" data-path="name">
</div>
</form>


Once loaded, any inputs in the second form should have a listener attached via keyup, which also seems to be fine.

On keyup we do indeed get into the keyup function, however we are not getting past the $input.each() function and the data-path attribute is not being seen.

In the console.log output, we get to "1. got here", but not to "2. got here".

I have tried numerous things, to no avail. Can anyone spot what the heck is going on here?

jQuery in use is 1.11.3

var mySelector, days = [];
$('#selector').on('change', function() {
var theType = $(this).val();
if(theType != ''){
$('#formContent').load('forms/' + theType + '.html');
var mySelector = '#' + theType;
var element = {}, $input = $(mySelector + ' input,' + mySelector + ' textarea,' + mySelector + ' select');
$(document).on('keyup', $input, function() {
// WE GET THIS FAR
console.log('1. got here.');
element = {};
$input.each(function(e) {
console.log('2. got here.');
if ($(this).data('path')) {
console.log('3. got here. ' + $(this).data('path'));
}
});
});
}
});

Answer

I think it's because you're not using the .load complete function as a callback. Your code is finished before the data is present:

var mySelector, days = [];
$('#selector').on('change', function() {
    var theType = $(this).val();
    if(theType != ''){
        $('#formContent').load('forms/' + theType + '.html', function ( data ) { //data will be the response once completed. This is only needed if you need to do something with the response data
        var mySelector = '#' + theType;
        var element = {}, $input = $(mySelector + ' input,' + mySelector + ' textarea,' + mySelector + ' select');
        $(document).on('keyup', $input, function() {
            // WE GET THIS FAR
            console.log('1. got here.');
            element = {};
            $input.each(function(e) {
                console.log('2. got here.');
                if ($(this).data('path')) {
                    console.log('3. got here. ' + $(this).data('path'));
                }
            });
        });
      });
    }
});
Comments