J. Smith J. Smith - 1 month ago 13
jQuery Question

Changing DOM with jQuery

I am trying to perform an AJAX request to change DOM. have this HTML:

<div class="input-field col s12 l6">
<input type="date" class="date datepicker" name="date" required>
<label for="date">Date</label>
</div>
<div class="input-field col s12 l6 hour">
<select class="select-hour" name="time">
<option value=""selected>No options available</option>
</select>
<label>Label</label>
</div>


And this is my JS:

$(".date").change(function(e){
$.ajax({
type: 'POST',
url: '/reserve }}',
data: {
date: $(this).val(),
},
success: function (data) {
var selectDropdown = $(this).parent().next().find('select').empty();
selectDropdown.append(data);
}
});
});


When I receive the options from the server I want to append them in the select but it is not working. Please help.

Answer

Try that, this isn't the same on the function(e){ ... } and success: function (data) { ... }.

See scope

$(".date").change(function(e){
    var $this = $(this);
    $.ajax({
        type: 'POST',
        url: '/reserve }}',
        data: {
            date: $this.val(),
        },
        success: function (data) {
            var selectDropdown = $this.parent().next().find('select').empty();
            selectDropdown.append(data);
        }
    });
});