I am trying to get JQuery to work on dynamically loaded content through ajax with event binding, similar to this: Event binding on dynamically created elements?
However, I am not that good with java/Jquery and I cant seem to get jquery to work on the ajax content. I started with this code:
(function($){
function floatLabel(inputType){
$(inputType).each(function(){
var $this = $(this);
var text_value = $(this).val();
// on focus add class "active" to label
$this.focus(function(){
$this.next().addClass("active");
});
// on blur check field and remove class if needed
$this.blur(function(){
if($this.val() === '' || $this.val() === 'blank'){
$this.next().removeClass();
}
});
// Check input values on postback and add class "active" if value exists
if(text_value!==''){
$this.next().addClass("active");
}
});
// Automatically remove floatLabel class from select input on load
//$( "select" ).next().removeClass();
}
// Add a class of "floatLabel" to the input field
floatLabel(".floatLabel");
});
And I tried to bind the events like this:
(function($){
var $this = $('.floatLabel');
var text_value = $('.floatLabel').val();
$('.container').on('focus', '.floatLabel', function floatLabel(inputType){
$(inputType).each(function(){
$this.next().addClass('active');
if(text_value!==''){
$this.next().addClass('active');
}
});
});
$('.container').on('blur', '.floatLabel', function floatLabel(inputType){
$(inputType).each(function(){
if($this.val() === '' || $this.val() === 'blank'){
$this.next().removeClass();
}
});
});
})(jQuery);
And this is the main html page:
<div class="container">
<div id="ha">
<script type="text/javascript">
$( document ).ready(function() {
$('#ha').load('example.com/createform');
});
</script>
</div>
</div>
Content loaded:
<div >
<input class="floatLabel" name="example">
<label for="example">example</label>
</div>