Reputation: 465
I see all sorts of answers online but none of them seem to be working for me.
This is for our local intranet. I'm adding inputs to a form dynamically when a user clicks a button. I have on focus/blur events but they aren't catching focus and blur on the dynamically created textboxes. I'm using .on for blur/focus but it still isn't working how I think it should. I've tried adding "input[type=text]" to the .on function as a selector but that doesn't work either. I've also tried giving the inputs a class and using that instead of input[type=text] but it still won't work.
I'm using the blur/focus to put in default values so the user knows what the textbox is for. I'm aware of the html5 placeholder but that won't work on IE9 which some of our computers still have.
html
<div id="details" class="miSections relative">
<div class="sectionHeader relative">Details<button id="detailButton" class="newButton" type="button">Add Another Detail</button></div>
<table id="detailsTable" class="infoTable">
<tr>
<td><input type="text" name="detDate_1" id="detDate_1" class="textarea defaultText" autocomplete="off" title="Detail Date"/></td>
</tr>
</table>
</div>
css
.infoTable{
text-align: center;
width:100%;
}
.defaultText{
color: #a1a1a1;
font-style: italic;
}
javascript
$(document).ready(function () {
$('.textarea').on('focus', function () {
//using .on('focus','.textarea',function() doesn't work
if ($(this).val() == $(this).attr('title')) {
$(this).removeClass('defaultText');
$(this).val("");
}
});
$('.textarea').on('blur', function () {
if ($(this).val() == "" || $(this).val() == $(this).attr('title')) {
$(this).addClass('defaultText');
$(this).val($(this)[0].title);
} else { $(this).removeClass('defaultText'); }
});
//fire the blur events to populate the inputs with default values
blurIt();
$('#detailButton').on('click', function () {
$('#detailsTable tr:last-child').after('><tr><td><input type="text" name="detDate_2" id="detDate_2" class="textarea defaultText" autocomplete="off" title="Detail Date"/></td></tr>');
blurIt();
countIt();
});
});
function blurIt(){
$('.textarea').blur();
}
function countIt(){
var inputs = $('.textarea').length;
console.log(inputs);
}
Upvotes: 3
Views: 4533
Reputation: 207901
Use .on()'s event delegation syntax.
Change:
$('.textarea').on('focus', function () {
//and
$('.textarea').on('blur', function () {
to:
$(document).on('focus', '.textarea', function () {
//and
$(document).on('blur', '.textarea',function () {
Note that you might gain some efficiency by using $('#details')
instead of $(document)
in my example.
Upvotes: 6