0

I am currently using the following code to tie in an event that limits input into a dynamicly created set of text boxes.

function createSomeTextBoxes() {
    //code here to add text boxes
    $('.PointerSPSLText').on('keyup', function() { charaterCount( $(this).attr('id'), 30 ) });
    $('.SPSLText').on('keyup', function() { charaterCount( $(this).attr('id'), 30 ) });
}

The problem I am having is that these events only get tied to the first element of the class it finds, since there can be more than one of each, that is a problem. I used to use the .live event for this and I could declare it once when the DOM was loaded and jquery took care of the rest. Is there a way to mimic the .live event or what is the best way to achieve the results I need?

4 Answers4

1

For dynamical created element, I think you must use event delegation like:

$("body").on("keyup", ".PointerSPSLText", function() {
   charaterCount( $(this).attr('id'), 30 )
});
$("body").on("keyup", ".SPSLText", function() {
   charaterCount( $(this).attr('id'), 30 )
});

More info at about on(): http://api.jquery.com/on/

Irvin Dominin
  • 29,799
  • 9
  • 75
  • 107
0

Yeah right live is deprecated now,

You can use dynamic on version like this,

 $('#some_static_parent_that_holds_PointerSPSLText').on('keyup','.PointerSPSLText', function(){});
rAjA
  • 871
  • 8
  • 13
0

New versions of jQuery use the on event instead of live to bind event handlers to dynamic elements.

function createSomeTextBoxes() {
    //code here to add text boxes
    $(document).on('keyup', '.PointerSPSLText', function() { 
       charaterCount( $(this).attr('id'), 30 ) 
    });
    $(document).on('keyup','.SPSLText', function() { 
       charaterCount( $(this).attr('id'), 30 ) 
    });
}

Notice that the event handler is bound to the document instead of a selector for the elements. The selector is specified as the second argument to the on function. When an event is triggered it propagates to the document which then inspects if the target matches the selector supplied as the second argument. You can bind to a static parent instead of the document for better performance.

Kevin Bowersox
  • 88,138
  • 17
  • 142
  • 176
0

If you only want to limit the character length, why not use the "maxlength" attribute of the input/textarea element, provided you have access to the function that generates the dynamic elements?

<input type="text" name="usrname" maxlength="30">
<textarea maxlength="30">Enter text here...</textarea>
lshettyl
  • 7,854
  • 4
  • 21
  • 28
  • only because the function limiting the length also places on onscreen error message under the textbox informing the user that they can only use 30 characters and if they need another then increase the quantity ordered – Morgan Richards Sep 05 '13 at 09:47
  • Shouldn't that be a label below the input box? It's more of an info than an error message. – lshettyl Sep 05 '13 at 10:03