(using jQuery)
1) I have a JavaScript click event that generates a form with a dropdown and a div like the following:
$('#closestDiv').on('click','.firstClick', function(event){
var pass = $(this).attr('data-pass');
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('id',"newForm");
f.setAttribute('action',"SubmitForm.php");
var d = document.createElement("select");
var op1 = new Option();
op1.value = "1";
op1.text = "1";
op1.setAttribute('class', "secondClick");
op1.setAttribute('data-pass', pass);
d.options.add(op1);
f.appendChild(d);
var div = document.createElement("div");
div.setAttribute('id', "newDiv");
div.innerHTML = 'REPLACE CONTENT';
f.appendChild(div);
$("#closestDiv").append(f);
}); // end on click
2) Next, I have an onclick event for the dropdown options that uses Ajax to load content into the div element.
$('#closestDiv').on('click', '.secondClick', function () {
$(this).prop('selected', true);
var value = $(this).attr('value');
var pass = $(this).attr('data-pass');
$.ajax({
url: 'getContent.php',
type: "get",
data : {value: value, pass: pass},
success: function(response){
var result = JSON.parse(response);
$('#newDiv').html(result['newContent']);
console.log(result['newContent']);
console.log($('#newDiv'));
} // end success function
}); // end ajax call
}); // end on click
While the console displays the correct new content and the div element shows the updated HTML with new content, the actual page displays "REPLACE CONTENT" (i.e., not updating).
I have successfully achieved this when the dropdown is loaded with the page rather than dynamically via JavaScript. I suspect that I might not fully understand the order in which the DOM loads elements and how to make this functionality work. Initially, I thought that constructing the dropdown with JavaScript would make it functional immediately, rather than relying on Ajax (which gives a similar result and is preferable if the solution is the same...).
Furthermore, I have observed that the dropdown does not reflect the selected option, even though the correct option is passed to Ajax.
Any guidance would be greatly appreciated. Thank you!