I’m having trouble changing a value of a hidden form element that was dynamically loaded via ajax. When a user clicks on a date, I’d like a few hidden input fields to get automatically updated with the day, month, and year (only day is shown in the code for simplification).
I suppose the main question is how can I select an element that has been dynamically loaded via ajax.
Simplified Code:
index.php
<a href="#" id="someLink">Click Me</a>
include.js
$(document).ready(function(){
$('#someLink').click(function(){
// Create modal dialog dynamically
var modal = $('<div/>').attr({
id:'new' + objectName + 'Modal',
class:'modal hide fade',
tabindex:'-1',
role:'dialog',
});
// Ajax call to load modal
$.ajax({
url: "getModal.php",
}).done(function ( data ) {
modal.html(data);
});
// show form
modal.modal('show');
return false;
});
// bind datepicker from jQuery UI to text input
$("body").on({
focus: function(){
$('.datepicker').datepicker({
onClose: function(dateText, inst) {
var inputName = $(this).attr("name"); //returns "startDate"
console.log($('#'+inputName+'_day')); // returns "[]"
$('#'+inputName+'_day').val(new Date(dateText).getDate());
}
});
}
},'.datepicker');
});
getModal.php
echo <?php
echo "<form name='modalForm'>";
echo "<input type='hidden' name='startDate_day' id='startDate_day'>";
echo "<input type='text' class='datepicker' name='startDate' id='startDate'>";
echo "</form>";
echo ?>
I was able to find the cause of the issue which I’m hoping will help someone else.
I use Grails/Rails and which automatically put a period character in the ID and I overlooked this. I was subsequently trying to use jQuery to call an element with a period in the name which will not work (because periods are reserved for class names).
I did create a jsfiddle showing the details in this question working successfully.